package com.cykj.pos.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cykj.common.annotation.DataSource;
import com.cykj.common.config.RuoYiConfig;
import com.cykj.common.constant.Constants;
import com.cykj.common.core.domain.AjaxResult;
import com.cykj.common.core.domain.entity.SysDictData;
import com.cykj.common.core.domain.entity.SysDictType;
import com.cykj.common.core.domain.entity.SysUser;
import com.cykj.common.core.domain.model.LoginUser;
import com.cykj.common.enums.DataSourceType;
import com.cykj.common.exception.CustomException;
import com.cykj.common.utils.SecurityUtils;
import com.cykj.common.utils.ServletUtils;
import com.cykj.common.utils.spring.SpringUtils;
import com.cykj.framework.web.service.TokenService;
import com.cykj.pos.domain.*;
import com.cykj.pos.domain.dto.*;
import com.cykj.pos.mapper.BizMerchTransactionsMapper;
import com.cykj.pos.mapper.BizMerchantInfoMapper;
import com.cykj.pos.mapper.BizMerchantMapper;
import com.cykj.pos.mapper.BizPosMachineMapper;
import com.cykj.pos.profit.dto.*;
import com.cykj.pos.service.*;
import com.cykj.pos.util.*;
import com.cykj.pos.websocket.server.WebSocketServer;
import com.cykj.system.mapper.SysUserMapper;
import com.cykj.system.service.ISysConfigService;
import com.cykj.system.service.ISysDictTypeService;
//import org.apache.commons.lang3.StringUtils;
import com.cykj.common.utils.StringUtils;
import com.cykj.system.service.ISysUserService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 终端设备信息Service业务层处理
 *
 * @author ruoyi
 * @date 2021-01-11
 */
@Service
public class BizPosMachineServiceImpl extends ServiceImpl<BizPosMachineMapper, BizPosMachine> implements IBizPosMachineService {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BizMerchantMapper bizMerchantMapper;

    @Autowired
    private  IBizPosMachineService iBizPosMachineService;

    @Autowired
    private IBizAllocAdjRecordsService iBizAllocAdjRecordsService;

    @Autowired
    private IBizMerchantService iBizMerchantService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;
    @Resource
    private BizMerchantInfoMapper bizMerchantInfoMapper;
    @Autowired
    private RuoYiConfig config;

    @Autowired
    private IBizPosMachineStatusRecordsService bizPosMachineStatusRecordsService;

    @Autowired
    IBizMerchBillService bizMerchBillService;

    @Autowired
    IBizWalletService walletService;

    @Autowired
    IBizMerchIntegralService merchIntegralService;

    @Autowired
    IBizPosPolicyService posPolicyService;

    @Autowired
    BizPosMachineMapper posMachineMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private IBizMerchOrderService merchOrderService;

    @Autowired
    private ISysConfigService configService;

    @Resource
    private SysUserMapper userMapper;
    @Resource
    BizPosMachineMapper bizPosMachineMapper;
    @Autowired
    private IBizPosTypeService posTypeService;
    @Resource
    BizMerchTransactionsMapper bizMerchTransactionsMapper;
    @Resource
    private com.cykj.pos.domain.PosPCommonParamConfig PosPCommonParamConfig;
    @Autowired
    private IAllocationRelationService iAllocationRelationService;

    @Autowired
    private ISettlementRateTemplateService iSettlementRateTemplateService;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public String doCallBacks(String s) {
        String s1= posMachineMapper.doCallBacks(s);
        return s1;
    }
    @Override
    public Long selVueCallBackmerchid(Long posId) {
        Long s5= posMachineMapper.selVueCallBackmerchid(posId);
        return s5;
    }
    @Override
    public Long posid(String s) {
        Long s4= posMachineMapper.posid(s);
        return s4;
    }
    @Override
    public int updataAllId(Long posId) {
        Date date=new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int ss= posMachineMapper.updataAllId(posId);
        /*查询pos表，getMerchId，getPosCode*/
        List<BizPosMachine> bizPosMachines=posMachineMapper.selectAll(posId);
        String posCode=bizPosMachines.get(0).getPosCode();
        BizMerchantEntry bizMerchantEntry=new BizMerchantEntry();
        bizMerchantEntry.setMerchId(bizPosMachines.get(0).getMerchId());
        bizMerchantEntry.setSn(bizPosMachines.get(0).getPosCode());
        int posrowsSize=posMachineMapper.selectAllBizMerchantEntry(posCode);
        if (posrowsSize>0){
            posMachineMapper.updateAllEntry(bizMerchantEntry);
        }else {
            posMachineMapper.insterAllEntry(bizMerchantEntry);
        }
        BizPosMachineStatusRecords bizPosMachineStatusRecords=new BizPosMachineStatusRecords();
        bizPosMachineStatusRecords.setTime(format.format(date));
        bizPosMachineStatusRecords.setSnCode(bizPosMachines.get(0).getPosCode());
        bizPosMachineStatusRecords.setActiveTime(format.format(date));
        int posSize=posMachineMapper.selectAllStatusRecords(posCode);
        if (posSize>0){
            posMachineMapper.updateAllStatusRecords(bizPosMachineStatusRecords);
        }else {
            posMachineMapper.inserterAllStatusRecords(bizPosMachineStatusRecords);
        }
        return ss;
    }
    @Override
    public BizPosMachine selectposCode(Long posId) {
        return bizPosMachineMapper.selectposCode(posId);
    }
    @Override
    @Transactional
    public Integer insertbaarecords(BizAllocAdjRecords bizAllocAdjRecords) {
        Integer s= posMachineMapper.insertbaarecords(bizAllocAdjRecords);
        return s;
    }
    @Override
    public HuaBoDTO getPersonByIds(Long s,Long merchId) {
        HuaBoDTO s1= posMachineMapper.getPersonByIds(s,merchId);
        return s1;
    }
    @Override
    public BizPosMachine poscode(Long s) {
        BizPosMachine s2= posMachineMapper.poscode(s);
        return s2;
    }
    @Override
    public Long selBizMerchantuserid(Long merchId) {
        Long s3= posMachineMapper.selBizMerchantuserid(merchId);
        return s3;
    }
    @Override
    public List<VueCallBack> queryListHuaBo(VueCallBack bizPosMachine) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser.getUserId() == 1){
            sysUser.setUserId(2L);
        }
        //当前时间
        Date date=new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, Object> data= bizPosMachine.getParams();
        String start = " 00:00:00";
        String end = " 23:59:59";
        if (!data.isEmpty()){
            Object beginTime=data.get("beginTime");
            Object endTime=data.get("endTime");
            String beginTimestr= beginTime.toString();
            String endTimestr= endTime.toString();
            bizPosMachine.setBeginTime(beginTimestr+ start);
            bizPosMachine.setEndTime(endTimestr+ end);
        }
        Map<String, Object> data1= bizPosMachine.getParams1();
        if (!data1.isEmpty()){
            Object beginTime1=data1.get("beginTime");
            Object endTime1=data1.get("endTime");
            String beginTimestr1= beginTime1.toString();
            String endTimestr1= endTime1.toString();
            bizPosMachine.setBeginTime1(beginTimestr1+ start);
            bizPosMachine.setEndTime1(endTimestr1+ end);
        }
        Long merchId = posMachineMapper.selectMerchId(sysUser.getUserId());
        if (bizPosMachine.getMerchId() == null) {
            bizPosMachine.setUserId(merchId);
        }
        if (bizPosMachine.getPageNo() != null && bizPosMachine.getPageSize() != null) {
            PageHelper.startPage(bizPosMachine.getPageNo(), bizPosMachine.getPageSize());
        }

        List<VueCallBack> list = posMachineMapper.getListHuaBo(bizPosMachine);
        return list;
    }
    @Override
    public List<VueCallBack> queryListExport(VueCallBack bizPosMachine) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser.getUserId() == 1){
            sysUser.setUserId(2L);
        }
        //当前时间
        Date date=new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, Object> data= bizPosMachine.getParams();
        String start = " 00:00:00";
        String end = " 23:59:59";
        if (!data.isEmpty()){
            Object beginTime=data.get("beginTime");
            Object endTime=data.get("endTime");
            String beginTimestr= beginTime.toString();
            String endTimestr= endTime.toString();
            bizPosMachine.setBeginTime(beginTimestr+ start);
            bizPosMachine.setEndTime(endTimestr+ end);
        }
        Map<String, Object> data1= bizPosMachine.getParams1();
        if (!data1.isEmpty()){
            Object beginTime1=data1.get("beginTime");
            Object endTime1=data1.get("endTime");
            String beginTimestr1= beginTime1.toString();
            String endTimestr1= endTime1.toString();
            bizPosMachine.setBeginTime1(beginTimestr1+ start);
            bizPosMachine.setEndTime1(endTimestr1+ end);
        }
        Long merchId = posMachineMapper.selectMerchId(sysUser.getUserId());
        if (bizPosMachine.getMerchId() == null) {
            bizPosMachine.setUserId(merchId);
        }
        List<VueCallBack> list = posMachineMapper.getListHuaBo(bizPosMachine);
        return list;
    }



    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<BizPosMachine> queryList(BizPosMachine bizPosMachine) {
        LambdaQueryWrapper<BizPosMachine> lqw = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(bizPosMachine.getPosName())){
            lqw.like(BizPosMachine::getPosName ,bizPosMachine.getPosName());
        }
        if (StringUtils.isNotBlank(bizPosMachine.getPosCode())){
            lqw.eq(BizPosMachine::getPosCode ,bizPosMachine.getPosCode());
        }
        if (StringUtils.isNotBlank(bizPosMachine.getPosType())){
            lqw.eq(BizPosMachine::getPosType ,bizPosMachine.getPosType());
        }
        if (StringUtils.isNotBlank(bizPosMachine.getPosActivateCode())){
            lqw.eq(BizPosMachine::getPosActivateCode ,bizPosMachine.getPosActivateCode());
        }
        if (StringUtils.isNotBlank(bizPosMachine.getPosActivateStatus())){
            lqw.eq(BizPosMachine::getPosActivateStatus ,bizPosMachine.getPosActivateStatus());
        }
        if (bizPosMachine.getPosBindTime() != null){
            lqw.eq(BizPosMachine::getPosBindTime ,bizPosMachine.getPosBindTime());
        }
        if (StringUtils.isNotBlank(bizPosMachine.getPosActivity())){
            lqw.eq(BizPosMachine::getPosActivity ,bizPosMachine.getPosActivity());
        }
        if (bizPosMachine.getPosDeposit() != null){
            lqw.eq(BizPosMachine::getPosDeposit ,bizPosMachine.getPosDeposit());
        }
        if (bizPosMachine.getPosCashback() != null){
            lqw.eq(BizPosMachine::getPosCashback ,bizPosMachine.getPosCashback());
        }
        if (StringUtils.isNotBlank(bizPosMachine.getPosModel())){
            lqw.eq(BizPosMachine::getPosModel ,bizPosMachine.getPosModel());
        }
        if (bizPosMachine.getMerchId() != null){
            lqw.eq(BizPosMachine::getMerchId ,bizPosMachine.getMerchId());
        }
        if (StringUtils.isNotBlank(bizPosMachine.getVar1())){
            lqw.eq(BizPosMachine::getVar1 ,bizPosMachine.getVar1());
        }
        if (StringUtils.isNotBlank(bizPosMachine.getVar2())){
            lqw.eq(BizPosMachine::getVar2 ,bizPosMachine.getVar2());
        }
        if (StringUtils.isNotBlank(bizPosMachine.getVar3())){
            lqw.eq(BizPosMachine::getVar3 ,bizPosMachine.getVar3());
        }
        if (StringUtils.isNotBlank(bizPosMachine.getVar4())){
            lqw.eq(BizPosMachine::getVar4 ,bizPosMachine.getVar4());
        }
        if (StringUtils.isNotBlank(bizPosMachine.getVar5())){
            lqw.eq(BizPosMachine::getVar5 ,bizPosMachine.getVar5());
        }
        return this.list(lqw);
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<BizPosMachine> getMachinesOfAllMerchantsWithQueryConditions(List<BizMerchant> merchants,BizPosMachine machine){
        List<BizPosMachine> machineList = new ArrayList<>();
        String posType = machine.getPosType();
        String posName = machine.getPosName();
        String posSNCode = machine.getPosCode();
        String posStatus = machine.getPosActivateStatus();

        List<Object> paramList = new ArrayList<>();
        StringBuilder sets = new StringBuilder();
        for(BizMerchant merchant: merchants){
            sets.append(merchant.getMerchId()).append(",");
        }
        String merchIdSets = sets.substring(0,sets.lastIndexOf(","));
        paramList.add(merchIdSets);

        StringBuilder sqlBuilder = new StringBuilder("select * from biz_pos_machine where  FIND_IN_SET(merch_id,?)");

        if(StringUtils.isNotBlank(posType)){
            paramList.add(posType);
            sqlBuilder.append(" and pos_type=?");
        }
        if(StringUtils.isNotBlank(posStatus)){
            paramList.add(posStatus);
            sqlBuilder.append(" and pos_activate_status=?");
        }
        if(StringUtils.isNotBlank(posSNCode)){
            paramList.add(posSNCode);
            sqlBuilder.append(" and pos_code=?");
        }
        if(StringUtils.isNotBlank(posName)){
            paramList.add("%"+posName+"%");
            sqlBuilder.append(" and pos_name like ?");
        }
        Object[] params = paramList.toArray();
        return jdbcTemplate.query(sqlBuilder.toString(),params,new BeanPropertyRowMapper<BizPosMachine>(BizPosMachine.class));
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<BizPosMachine> getPosMachineByMerchId(Long merchId){
        LambdaQueryWrapper<BizPosMachine> posQuery = Wrappers.lambdaQuery();
        posQuery.eq(BizPosMachine::getMerchId ,merchId);
        return this.list(posQuery);
    }
    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<BizPosMachine> getPosMachinesByMerchId(Long merchId){
        String sql = "select * from biz_pos_machine where FIND_IN_SET(merch_id,findMerchSubNode(?))";
        return jdbcTemplate.query(sql,new Object[]{merchId},
                new BeanPropertyRowMapper<BizPosMachine>(BizPosMachine.class));
    }
    private  String queryCondtions(List<Object> paramList, PosTerminalDTO terminalVo,int pageNo,int pageSize){
        StringBuilder conditions = new StringBuilder(" ");
        String posName = terminalVo.getPosName();
        String posSNCode = terminalVo.getPosCode();
        String posType = terminalVo.getPosType();
        String posStatus =terminalVo.getPosActivateStatus();
        String posMachineType = terminalVo.getPosMachineType();
        if(StringUtils.isNotBlank(posType)){
            paramList.add(posType);
            conditions.append(" and find_in_set(pos_type,?)");
        }
        if(StringUtils.isNotBlank(posStatus)){
            paramList.add(posStatus);
            conditions.append(" and pos_activate_status=?");
        }
        if(StringUtils.isNotBlank(posSNCode)){
            paramList.add(posSNCode);
            conditions.append(" and pos_code like CONCAT(?,'%')");
        }
        if(StringUtils.isNotBlank(posMachineType)){
            paramList.add(posMachineType);
            conditions.append(" and find_in_set(var1,?)");
        }
        if(StringUtils.isNotBlank(posName)){
            paramList.add(posName);
            conditions.append(" and pos_name like CONCAT(?,'%')");
        }
        // 加排序 order by pos_code asc
        conditions.append(" order by pos_code asc");
        long start = (pageNo -1) * pageSize;
        if(pageNo != -1 && pageSize != -1){
            paramList.add(start);
            paramList.add(pageSize);
            conditions.append(" LIMIT ?,?");
        }
        return conditions.toString();
    }
    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<BizPosMachine> getPosMachinesByMerchId(Long merchId, PosTerminalDTO terminalVo){
        List<Object> paramList = new ArrayList<>();
        StringBuilder sqlBuilder = new StringBuilder("select * from biz_pos_machine where FIND_IN_SET(merch_id,findMerchSubNode(?))");
        paramList.add(merchId);
        sqlBuilder.append(this.queryCondtions(paramList,terminalVo,-1,-1));
        Object[] params = paramList.toArray();
        return jdbcTemplate.query(sqlBuilder.toString(),params, new BeanPropertyRowMapper<BizPosMachine>(BizPosMachine.class));
    }
    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<MachineTransferDTO> getPagePosMachinesByMerchId(Long merchId, PosTerminalDTO terminalVo,int pageNo,int pageSize){
        List<Object> paramList = new ArrayList<>();
        long start = (pageNo - 1)* pageSize;
        Integer operType = terminalVo.getOperType();
        StringBuilder sqlBuilder = null;
        if(operType != null){
            if(1 == operType){
                //仅能划拔本级终端
                sqlBuilder = new StringBuilder("SELECT * FROM biz_pos_machine WHERE  merch_id=? AND " +
                        "pos_code NOT IN (SELECT sn_code FROM biz_pos_machine_status_records) ");
            }
            if(2 == operType){
                //仅能回调下拉下级终端
                sqlBuilder = new StringBuilder("select * from biz_pos_machine where merch_id in (select merch_id from biz_merchant where parent_id=?) ");
            }
        }else{
            // sqlBuilder = new StringBuilder("select * from biz_pos_machine where FIND_IN_SET(merch_id,findMerchSubNode(?))");
            sqlBuilder = new StringBuilder("select m.*,r.records_type recordsType from biz_pos_machine m LEFT JOIN biz_pos_machine_status_records r ON m.pos_code=r.sn_code WHERE merch_id=? ");
        }
        paramList.add(merchId);
        sqlBuilder.append(this.queryCondtions(paramList,terminalVo,pageNo,pageSize));
        Object[] params = paramList.toArray();
        return jdbcTemplate.query(sqlBuilder.toString(),params, new BeanPropertyRowMapper<MachineTransferDTO>(MachineTransferDTO.class));
    }
    @Override
    public List<TerminalDTO> getPosByMerchId(PosTerminalDTO terminalDTO) {
        Integer operType = terminalDTO.getOperType();
        List<TerminalDTO> list = new ArrayList<>();
        // 处理分页
        if(terminalDTO.getPageNo()!=-1 && terminalDTO.getPageSize()!=-1){
            int start = (terminalDTO.getPageNo()-1)*terminalDTO.getPageSize();
            terminalDTO.setStart(start);
        }
        if(operType !=null){
            if(1 == operType){
                //仅能划拔本级终端
                list= posMachineMapper.getAllPos(terminalDTO);
            }
            if(2 == operType){
                //仅能回调下拉下级终端
               list= posMachineMapper.getAllPosTwo(terminalDTO);
            }
        }else{
            list= posMachineMapper.getAllPosNull(terminalDTO);
        }
        return list;
    }
    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<BizPosMachine> getPosMachinesByInteval(PosTerminalDTO terminalDTO){
        BizMerchant merchant = iBizMerchantService.getMerchantByUserId(terminalDTO.getUserId());
        Long merchantId = merchant.getMerchId();
        LambdaQueryWrapper<BizPosMachine> posQuery = Wrappers.lambdaQuery();
        posQuery.eq(BizPosMachine::getMerchId ,merchantId);
        posQuery.eq(BizPosMachine::getPosActivateStatus,terminalDTO.getPosActivateStatus());
        posQuery.eq(BizPosMachine::getChannel,terminalDTO.getChannel());
        posQuery.between(BizPosMachine::getPosCode,terminalDTO.getPosCodeStart(),terminalDTO.getPosCodeEnd());
        return this.list(posQuery);
    }
    @Override
    @DataSource(DataSourceType.SLAVE)
    public Long getPosMachineCountsByMerchId(Long merchId){
        String sql = "select count(1) from biz_pos_machine where merch_id=? and pos_name!='虚拟'";
        return jdbcTemplate.queryForObject(sql,new Object[]{merchId},Long.class);
    }
    @Override
    public int interRecords(BizPosMachineStatusRecords inbizPosMachineStatusRecords){
        return posMachineMapper.interRecords(inbizPosMachineStatusRecords);
    }
    @Override
    public int updatebizPosMachine(String sn){
        return posMachineMapper.updatebizPosMachine(sn);
    }
    @Override
    @DataSource(DataSourceType.SLAVE)
    public Long getPosMachineActivatedCountsByMerchId(Long merchId){
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT count(*) FROM biz_pos_machine_status_records r ");
        sql.append("WHERE r.records_type='2' and r.sn_code IN ");
        sql.append(" (SELECT pos_code FROM biz_pos_machine WHERE merch_id=?) ");
        return jdbcTemplate.queryForObject(sql.toString(),new Object[]{merchId},Long.class);
    }
    @Override
    @DataSource(DataSourceType.SLAVE)
    public Long getPosMachineNotActivatedAndBindCountsByMerchId(Long merchId){
        StringBuffer sql = new StringBuffer();
        sql.append("select count(1) from biz_pos_machine where merch_id=? and pos_code not in  ");
        sql.append("( select sn_code from biz_pos_machine_status_records )");
        return jdbcTemplate.queryForObject(sql.toString(),new Object[]{merchId},Long.class);
    }
    @Override
    @DataSource(DataSourceType.SLAVE)
    public Integer getPosMachineActivatedCountsByMerchId(Long merchId,String thisMonth){
        LocalDate localDate = LocalDate.now();
        String formatedDate = localDate.format(DateTimeFormatter.ofPattern("yyyyMMdd")).substring(0,6);
        if("last".equals(thisMonth)){
            LocalDate newDate = LocalDate.now();
            newDate.minusMonths(1);
            formatedDate = newDate.format(DateTimeFormatter.ofPattern("yyyyMMdd")).substring(0,6);
        }
        String sql = "select count(1) from biz_pos_machine where FIND_IN_SET(merch_id,findMerchSubNode(?)) and pos_activate_status='2' and pos_bind_time like ?";
        return jdbcTemplate.queryForObject(sql,new Object[]{merchId,"'"+formatedDate+"%'"},Integer.class);
    }
    @Override
    @Transactional
    public Integer doTheOperations(List<Long> posIdList, Long merchantId, Long loginUser,Integer operType,Long orderId){
        if(2==operType){// 回调
            List<BizPosMachine> posList = iBizPosMachineService.listByIds(posIdList);
            List<BizAllocAdjRecords> recordList = new ArrayList<>();
            LocalDateTime localDate = LocalDateTime.now();
            String formatedDate = localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            for(BizPosMachine pos:posList){
                //划拔操作记录
                BizAllocAdjRecords record = new BizAllocAdjRecords();
                BizMerchant oldMerchant = iBizMerchantService.getById(pos.getMerchId());
                BizMerchant newMerchant = iBizMerchantService.getById(loginUser);
                record.setPosId(pos.getPosId());
                record.setOldUserId(oldMerchant.getUserId());
                record.setNewUserId(newMerchant.getUserId());
                record.setPosCode(pos.getPosCode());
                record.setOperator(loginUser);
                record.setOperateTime(formatedDate);
                record.setOperateType(operType);
                recordList.add(record);
                pos.setVar2(newMerchant.getMerchCode());
                pos.setMerchId(loginUser);
            }
            iBizPosMachineService.updateBatchById(posList);
            iBizAllocAdjRecordsService.saveBatch(recordList);
            return posIdList.size();

        }else {// 划拨
            // 生成订单  改变订单状态
            BizMerchOrder merchOrder = null;
            if (orderId != null && orderId != 0) {
                BizTimeoutIntegral bizTimeoutIntegral = merchOrderService.queryOrderByOrderId(orderId);// 通过orderId查询临时积分表
                if (bizTimeoutIntegral!=null){// 说明是积分兑换
                    if (bizTimeoutIntegral.getTimeout()==1){// 超时
                        //  改变订单状态   走订单
                        merchOrder = merchOrderService.getById(orderId);
                        merchOrder.setStatus(2);// 超时
                        merchOrderService.saveOrUpdate(merchOrder);
                    }else {// 未超时
                        //  改变订单状态   走订单
                        merchOrder = merchOrderService.getById(orderId);
                        merchOrder.setStatus(1);
                        merchOrderService.saveOrUpdate(merchOrder);
                        // 把积分给人家打过去
                        merchOrderService.saveTemporaryIntegral(bizTimeoutIntegral);
                    }
                }else {
                    //  改变订单状态   走订单
                    merchOrder = merchOrderService.getById(orderId);
                    merchOrder.setStatus(1);
                    merchOrderService.saveOrUpdate(merchOrder);
                }

            }
            // 发消息
            BizMessageRecords messageRecords = new BizMessageRecords();
            // 发消息   1- 入库
            String rukuMess = "您的机具已经下发，共" + posIdList.size() + "台机具，请注意查收";
            messageRecords.setMsgContent(rukuMess);// 消息内容
            messageRecords.setMsgType(1); // 消息类型  入库
            messageRecords.setReadStatus(0);// 消息未读
            messageRecords.setAdviceType(1); // 业务消息
            BizMerchant merchant = iBizMerchantService.getMerchantByMerchId(merchantId);
            webSocketServer.sendInfo(merchant.getUserId(), messageRecords);// 发送消息

            List<BizPosMachine> posList = iBizPosMachineService.listByIds(posIdList);
            List<BizAllocAdjRecords> recordList = new ArrayList<>();
            LocalDateTime localDate = LocalDateTime.now();
            String formatedDate = localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            for (BizPosMachine pos : posList) {
                if ("1".equals(pos.getPosActivateStatus())) continue;
                //划拔操作记录
                BizAllocAdjRecords record = new BizAllocAdjRecords();
                BizMerchant oldMerchant = iBizMerchantService.getById(pos.getMerchId());
                BizMerchant newMerchant = iBizMerchantService.getById(merchantId);
                record.setPosId(pos.getPosId());
                record.setOldUserId(oldMerchant.getUserId());
                record.setNewUserId(newMerchant.getUserId());
                record.setPosCode(pos.getPosCode());
                record.setOperator(loginUser);
                record.setOperateTime(formatedDate);
                record.setOperateType(operType);
                // 设置消息id
                record.setMsgId(messageRecords.getMsgId());
                // 如果是积分兑换  需要存储订单编号
                if (merchOrder != null) {
                    record.setVar1(merchOrder.getOrderNo());
                }
                recordList.add(record);
                pos.setVar2(newMerchant.getMerchCode());
                pos.setMerchId(merchantId);
            }
            PosTerminalDTO terminalDTO=new PosTerminalDTO();
            terminalDTO.setMerchId(merchantId);
//            List<TerminalDTO> list= posMachineMapper.getAllPosNull(terminalDTO);
//            List<TerminalDTO> ll=new ArrayList<>();
//            int num = 0;
//            for(TerminalDTO l:list){
//               if(l.getRecordsType()!="0"){
//                   num++;
//               }
//            }
//            if(num>5){
                iBizPosMachineService.updateBatchById(posList);
                iBizAllocAdjRecordsService.saveBatch(recordList);
//            }else {
//                return ll.size();
//            }
            return posIdList.size();
        }
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public List<Map<String,Object>> getPosFilterConditions(){
        List<Map<String,Object>> dictList = new ArrayList<>();
        List<String> typeList = config.getPosQueryFilterConditions();
        for(String type:typeList){
            Map<String,Object> dict = new HashMap<>();
            SysDictType dictType = iSysDictTypeService.selectDictTypeByType(type);
            List<SysDictData> dictData = iSysDictTypeService.selectDictDataByType(type);
            dict.put("dictType",dictType);
            dict.put("dictData",dictData);
            dictList.add(dict);
        }
        return dictList;
    }
    @Override
    @DataSource(DataSourceType.SLAVE)
    public BizPosMachine getPosMachineBySnCode(String snCode){
        LambdaQueryWrapper<BizPosMachine> posQuery = Wrappers.lambdaQuery();
        posQuery.eq(BizPosMachine::getPosCode ,snCode);
        return this.getOne(posQuery);
    }

    @Override
    public BizPosMachineStatusRecords getRecordsBySnCode(String snCode){
        return posMachineMapper.getRecordsBySnCode(snCode);
    }

    @Override
    @Transactional
    public KuaiQianResult posMachineActivate(TerminalActivateDTO terminalActivateDTO) {
        // 判断设备是否激活
        String snCode = terminalActivateDTO.getSnCode();
        BizPosMachineStatusRecords posMachineStatusRecords = bizPosMachineStatusRecordsService.getPosMachineBindActionRecordsBySnCode(snCode,"2");
        if(posMachineStatusRecords!=null){
            return new KuaiQianResult("03","该设备存在激活信息，无需重复激活");
        }
        // 根据merchant_id获得绑定的记录信息
        String merchantId = terminalActivateDTO.getMerchantId();
        posMachineStatusRecords = bizPosMachineStatusRecordsService.getPosMachineBindActionRecordsBySnCode(snCode);
        // BizPosMachineStatusRecords posMachineStatusRecords = new BizPosMachineStatusRecords();
        // posMachineStatusRecords.setPhoneNo(terminalActivateDTO.getPhoneNo());
        // posMachineStatusRecords.setTerminalId(terminalActivateDTO.getTerminalId());
        // posMachineStatusRecords.setDeviceType(terminalActivateDTO.getDeviceType());
        // posMachineStatusRecords.setSnCode(terminalActivateDTO.getSnCode());
        // posMachineStatusRecords.setDirectlyOrgId(terminalActivateDTO.getDirectlyOrgID());
        //posMachineStatusRecords.setMerchantId(terminalActivateDTO.getMerchantId());
        posMachineStatusRecords.setIsActivated(terminalActivateDTO.getIsActivated());
        posMachineStatusRecords.setReceiptType(terminalActivateDTO.getReceiptType());
        posMachineStatusRecords.setName(terminalActivateDTO.getName());
        posMachineStatusRecords.setActiveTime(terminalActivateDTO.getActiveTime());
        posMachineStatusRecords.setIdTxn(terminalActivateDTO.getIdTxn());
        posMachineStatusRecords.setSecondOrgId(terminalActivateDTO.getSecondOrgID());
        posMachineStatusRecords.setOrderId(terminalActivateDTO.getOrderId());
        posMachineStatusRecords.setPolicyId(terminalActivateDTO.getPolicyId()); // 政策编号
        // -------------------自己扩展内容--------------------------
        LocalDateTime localDateTime = LocalDateTime.now();
        String receiptDate = DateUtils.localeDateTime2String(localDateTime, Constants.DATETIME_FORMATTER);
        posMachineStatusRecords.setReceiptDate(receiptDate); // 设置接收时间
        posMachineStatusRecords.setRecordsType("2"); //该记录是设备激活操作记录
        // 保存设备状态记录
        bizPosMachineStatusRecordsService.saveOrUpdate(posMachineStatusRecords);
        System.out.println("-----------------------激活信息打印-----------------------");
        System.out.println(posMachineStatusRecords);
        System.out.println("----------------------------------------------------------");
        // 获得政策信息  重要就是这块
        // BizPosPolicy posPolicy = posPolicyService.getPosPolicyByPolicyId(terminalActivateDTO.getPolicyId());
        // 通过设备号获得商户信息
        BizPosMachine posMachine = getPosMachineBySnCode(terminalActivateDTO.getSnCode());
        // 获得pos机类型   查看他的返现  返积分情况
        String posTypeId = posMachine.getPosType();
        // 处理一下数据库为null或者""的情况
        posTypeId = StringUtils.isEmpty(posTypeId) || posTypeId==null ?"1":posTypeId;
        BizPosType posType = posTypeService.getPosTypeById(Long.parseLong(posTypeId));
        Double returnMoney = 120.00; // 默认返现金额
        Double returnTaxation = 0.09;// 默认税点
        Long returnIntegral = 120L; // 通用积分
        // 获得政策中的返现金额
        if(posType!=null){
            returnMoney = posType.getReturnMoney().doubleValue();
            returnTaxation = posType.getTaxation().doubleValue();
            returnIntegral = posType.getReturnIntegral();
        }
        //向商户账单表中插入数据
        //--------------------- 插入账单  返现 1--------------------------
        // 更新pos机器状态
        posMachine.setPosActivateStatus("2");//状态为2是激活
        saveOrUpdate(posMachine);//更新pos机
        Long merId = posMachine.getMerchId();
        // 获得商户
        BizMerchant bizMerchant = iBizMerchantService.getMerchantByMerchId(merId);
        // 获得用户id
        Long userId = bizMerchant.getUserId();
        // 返现发消息
        // String fanXianMess = "返现："+returnMoney*(1-returnTaxation)+"元";
        String fanXianMess = "返现："+returnMoney+"元";
        BizMessageRecords fanXianMessageRecords = new BizMessageRecords();
        fanXianMessageRecords.setMsgContent(fanXianMess);// 消息内容
        fanXianMessageRecords.setMsgType(2); // 消息类型  返现   机具激活返现
        fanXianMessageRecords.setReadStatus(0); // 消息未读
        fanXianMessageRecords.setAdviceType(1); // 业务消息
        webSocketServer.sendInfo(userId,fanXianMessageRecords);// 发送消息
        System.out.println("-----------------------返现发消息打印-----------------------");
        System.out.println(fanXianMessageRecords);
        System.out.println("----------------------------------------------------------");
        // 账单信息
        BizMerchBill merchBill = new BizMerchBill();
        BizMerchant merchant = iBizMerchantService.getMerchantByMerchId(merId);
        merchBill.setMerchId(posMachine.getMerchId());//POS机器的主人
        merchBill.setMerchName(terminalActivateDTO.getName()); // 名称
        merchBill.setPosType(posMachine.getPosType()); // 设备类型
        merchBill.setPosCode(posMachine.getPosCode()); // 设备编号
        merchBill.setBillType("1"); // 账单类型  返现
        // BigDecimal amount = new BigDecimal(returnMoney*(1-returnTaxation));
        BigDecimal amount = new BigDecimal(returnMoney);
        merchBill.setAmount(amount.setScale(2,BigDecimal.ROUND_HALF_UP));// 返现金额  四射侮辱
        merchBill.setPolicyId(terminalActivateDTO.getPolicyId());//正常id  默认设置成1001
        merchBill.setBillDate(DateUtils.localeDateTime2String(localDateTime, Constants.DATETIME_FORMATTER)); // 账单日期
        BigDecimal taxation = new BigDecimal(returnMoney*returnTaxation);
        merchBill.setTaxation(taxation.setScale(2,BigDecimal.ROUND_HALF_UP)); // 税点
        merchBill.setMsgId(fanXianMessageRecords.getMsgId());
        // 保存账单
        bizMerchBillService.saveOrUpdate(merchBill);
        System.out.println("-----------------------账单发信息打印-----------------------");
        System.out.println(merchBill);
        System.out.println("----------------------------------------------------------");
        Long merchId = posMachine.getMerchId();
        // 返积分发消息
        String jiFenMess = "返积分："+returnIntegral;
        BizMessageRecords jiFenMessageRecords = new BizMessageRecords();
        jiFenMessageRecords.setMsgContent(jiFenMess);// 消息内容
        jiFenMessageRecords.setMsgType(8); // 消息类型  返积分
        jiFenMessageRecords.setReadStatus(0);// 消息未读
        jiFenMessageRecords.setAdviceType(1); // 业务消息
        webSocketServer.sendInfo(userId,jiFenMessageRecords);// 发送消息
        //向商户积分表中插入数据
        //--------------------- 插入积分明细   激活机具--------------------------
        BizMerchIntegral merchIntegral = new BizMerchIntegral();
        merchIntegral.setMerchId(merchId);
        merchIntegral.setPosCode(posMachine.getPosCode());
        merchIntegral.setIntegralType("激活机具");
        merchIntegral.setValue(returnIntegral);
        merchIntegral.setTransType("1");//收入  支出2
        merchIntegral.setMsgId(jiFenMessageRecords.getMsgId());// 设置消息id
        // merchIntegral.setOrderId(UUID.randomUUID().toString().replaceAll("-","")); //订单编号
        merchIntegralService.saveOrUpdate(merchIntegral);
        System.out.println("-----------------------积分明细打印------------------------");
        System.out.println(merchIntegral);
        System.out.println("---------------------------------------------------------");
        //---------------------  更新钱包   ----------------------------
        // 1-通过user_id获取钱包
        BizWallet wallet = walletService.getMyWalletByUserId(userId);
        // 更新数据
        String secProfitAmount = wallet.getProfitAmount();//获得结算账户余额
        String secRewardAmount = wallet.getRewardAmount();// 获得激活奖励账户
        String secIntegral = wallet.getIntegral(); // 通用积分
        String key = wallet.getSecretKey();// 获得key
        // 解密数据
        String profitAmountStr = DESHelperUtil.decrypt(key,secProfitAmount);
        String rewardAmountStr = DESHelperUtil.decrypt(key,secRewardAmount);
        String integralStr = DESHelperUtil.decrypt(key,secIntegral);
        // 转换成BigDecimal类型
        BigDecimal profitAmount = new BigDecimal(profitAmountStr);
        BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
        // 把钱加入到结算账户中
        //profitAmount = profitAmount.add(BigDecimal.valueOf(returnMoney*(1-returnTaxation)));
        // 把钱加入到激活奖励账户中
        rewardAmount = rewardAmount.add(BigDecimal.valueOf(returnMoney));
        BigDecimal walletAmount = profitAmount.add(rewardAmount);
        Long integral = Long.parseLong(integralStr);
        integral = integral+returnIntegral;// 通用积分
        // 加密
        String profitAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(profitAmount));
        String rewardAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(rewardAmount));
        String walletAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(walletAmount));
        String integralMoneyStr = DESHelperUtil.encrypt(key,String.valueOf(integral));
        wallet.setProfitAmount(profitAmountMoneyStr);
        wallet.setRewardAmount(rewardAmountMoneyStr);
        wallet.setWalletAmount(walletAmountMoneyStr);
        wallet.setIntegral(integralMoneyStr);
        wallet.setSecretKey(key);
        // 保存钱包信息
        walletService.saveOrUpdate(wallet);
        // 保存设备与伙伴团队的对应信息
        bizPosMachineStatusRecordsService.generatePosMerchantRelatedProcedure(snCode,merchId);
        return new KuaiQianResult("00","设备激活信息更新成功");
    }

    @Override
    @Transactional
    public KuaiQianResult posMachineBind(TerminalBindDTO terminalBindDTO) {
        //根据设备SN号查询设备是否被激活
        String snCode = terminalBindDTO.getSnCode();
        BizPosMachineStatusRecords posMachineStatusRecords = bizPosMachineStatusRecordsService.getPosMachineBindActionRecordsBySnCode(snCode,"1");
        if(posMachineStatusRecords!=null){
            return new KuaiQianResult("02","该设备存在绑定信息，无需重复绑定");
        }
        posMachineStatusRecords = new BizPosMachineStatusRecords();
        // ----------快钱接口提供数据--------------
        posMachineStatusRecords.setSnCode(snCode); // 设备SN码
        posMachineStatusRecords.setMerchantId(terminalBindDTO.getMerchantId()); // 商户标识
        posMachineStatusRecords.setTerminalId(terminalBindDTO.getTerminalId()); // 商户终端ID
        posMachineStatusRecords.setDeviceType(terminalBindDTO.getDeviceType()); // 设备类型
        posMachineStatusRecords.setReceiptType(terminalBindDTO.getReceiptType()); // 产品名称
        posMachineStatusRecords.setDirectlyOrgId(terminalBindDTO.getDirectlyOrgID()); // 直属机构号
        posMachineStatusRecords.setPhoneNo(terminalBindDTO.getPhoneNo()); // 手机号
        posMachineStatusRecords.setIdCardNo(terminalBindDTO.getIdCardNo());// 身份号
        posMachineStatusRecords.setTime(terminalBindDTO.getTime()); // 绑定时间
        posMachineStatusRecords.setStatus(terminalBindDTO.getStatus()); // 绑定状态
        // ---------------------------------------
        // -----------------下面是待接收的内容----------------------
        posMachineStatusRecords.setSecondOrgId(terminalBindDTO.getSecondOrgID());// 二级机构号
        posMachineStatusRecords.setName(terminalBindDTO.getName()); // 姓名
        // -------------------自己扩展内容--------------------------
        LocalDateTime localDateTime = LocalDateTime.now();
        String receiptDate = DateUtils.localeDateTime2String(localDateTime, Constants.DATETIME_FORMATTER);
        posMachineStatusRecords.setReceiptDate(receiptDate); // 设置接收时间
        posMachineStatusRecords.setRecordsType("1"); //该记录是设备绑卡操作记录
        boolean r = bizPosMachineStatusRecordsService.saveOrUpdate(posMachineStatusRecords);
        if(r)
            return new KuaiQianResult("00","设备绑定信息更新成功");
        return new KuaiQianResult("01","设备绑定信息更新失败");
    }

    @Transactional
    public void posMachineActivate(OrdinaryMerchantDTO ordinaryMerchantDTO){
        String snCode = ordinaryMerchantDTO.getSnCode();
//        String userName = ordinaryMerchantDTO.getMerchName();
//        String mobile = ordinaryMerchantDTO.getMarkedMobile();
        BizPosMachine machine = this.getPosMachineBySnCode(snCode);
//        Long parentMerchId = machine.getMerchId();
//        Long parentUserId = this.getUserIdByMerchId(parentMerchId);
//        //1.生成禁用状态的用户信息
//        SysUser user = new SysUser();
//        user.setUserName(mobile);
//        user.setStatus("1");//默认禁用
//        user.setNickName(userName);
//        user.setInviteUserId(parentUserId);
//        user.setPassword(SecurityUtils.encryptPassword("123456"));
//        sysUserService.insertUser(user);
//        //2.新增普通商户
//        BizMerchant merchant = new BizMerchant();
//        merchant.setMerchCode(this.generateMerchCode("CY"));
//        merchant.setMerchName(userName);
//        this.save(merchant);
        //3.更新机具状态为激活
        machine.setPosActivateStatus("1");
        this.updateById(machine);
    }

    @Override
    @DataSource(DataSourceType.SLAVE)
    public Integer getPosMachineAllCountsByMerchId(Long merchantId) {
        return posMachineMapper.getPosMachineAllCountsByMerchId(merchantId);
    }

	@Override
	@DataSource(DataSourceType.SLAVE)
	public List<MerchantsTransferDTO> getAllMerchantByNickName(String nickName) {
		List<MerchantsTransferDTO> posList =posMachineMapper.getAllMerchantByNickName(nickName);
		return posList;
	}

	@Override
    @Transactional
	public void updateMerchantsTransfer(BizPosMachine bizPosMachine) {
		LambdaUpdateWrapper<BizPosMachine> pos =Wrappers.lambdaUpdate();
		pos.eq(BizPosMachine::getPosCode,bizPosMachine.getPosCode());
        // 商户转移  删除pos机器对应的商户和pos机器的对应信息
        posMachineMapper.deleteMerchPosRelated(bizPosMachine.getPosCode());
        // 保存设备与伙伴团队的对应信息  重新绑定
        bizPosMachineStatusRecordsService.generatePosMerchantRelatedProcedure(bizPosMachine.getPosCode(),bizPosMachine.getMerchId());
		// 修改pos机器的商户id
        posMachineMapper.update(bizPosMachine,pos);
	}

    @Override
    public String importPosMachine(List<BizPosMachineTemporaryDTO> posList, boolean updateSupport, String operName) {
        return null;
    }
    /*@Override
    public String importPosMachine(List<BizPosMachine> posList, boolean isUpdateSupport, String operName) {
        //Long userId=userMapper.selectUserId(operName);
        if (StringUtils.isNull(posList) || posList.size() == 0)
        {
            throw new CustomException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (BizPosMachine posMachine : posList)
        {
            try
            {
                // 验证是否存在这个用户
                BizPosMachine posCode = posMachineMapper.selectPosCode(posMachine.getPosCode());
                if (StringUtils.isNull(posCode))
                {
//                    posMachine.setPassword(SecurityUtils.encryptPassword(password));
                    //posMachine.setCreateBy(userId);
                   String posType = posMachineMapper.selectPosType(posMachine.getPosType());
                   if (posType==null || "".equals(posType)){
                       posMachine.setPosType("9");
                   }
                   String var1 = posMachineMapper.selectVar1(posMachine.getVar1());
                   posMachine.setVar1(var1);
                   posMachine.setPosType(posType);
                    posMachine.setMerchId((long) 2);
                    posMachine.setPosActivateStatus("0");
                    //bizPosMachineMapper.insertPosMachine(posMachine);
                    saveOrUpdate(posMachine);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、pos机 " + posMachine.getPosCode() + " 导入成功");
                }
                *//*else if (isUpdateSupport)
                {
                    //posMachine.setUpdateBy(userId);
                   // bizPosMachineMapper.insertPosMachine(posMachine);
                    saveOrUpdate(posMachine);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、pos机 " + posMachine.getPosCode() + " 更新成功");

                }*//*
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、pos机 " + posMachine.getPosCode() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、pos机 " + posMachine.getPosCode() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }*/

    @Override
    @Transactional
    public int updateMerchantsTransferVue(BizPosMachine bizPosMachine) {
        LambdaUpdateWrapper<BizPosMachine> pos =Wrappers.lambdaUpdate();
        pos.eq(BizPosMachine::getPosCode,bizPosMachine.getPosCode());
        // 商户转移  删除pos机器对应的商户和pos机器的对应信息
        posMachineMapper.deleteMerchPosRelated(bizPosMachine.getPosCode());
        // 保存设备与伙伴团队的对应信息  重新绑定
        bizPosMachineStatusRecordsService.generatePosMerchantRelatedProcedure(bizPosMachine.getPosCode(),bizPosMachine.getMerchId());
        // 修改pos机器的商户id
        int i=posMachineMapper.update(bizPosMachine,pos);
        return i;
    }

    @Override
    public List<VueCallBack> queryListCallBack(VueCallBack bizPosMachine) {
        List<VueCallBack> list=posMachineMapper.getListCallBack(bizPosMachine);
        return list;
    }

    @Override
    @Transactional
    public int doCallBack(String code) {
        // 获取当前的用户
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();
        if (sysUser.getUserId() == 1L) {
            sysUser.setUserId(2L);
        }
        posMachineMapper.doCallBack(code, sysUser.getUserId());
        return 1;
    }

    @Override
    public VueCallBack getPersonById(String posId) {
        VueCallBack s= posMachineMapper.getPersonById(posId);
        return s;
    }

    @Override
    public BizPosMachineSyncDTO selectBizPosMachinesn(String posCode) {
        BizPosMachineSyncDTO s= posMachineMapper.selectBizPosMachinesn(posCode);
        if (s==null){
            return posMachineMapper.selectBizPosMachineNewsn(posCode);
        }else {
            return s;
        }
    }
    @Override
    public int doTransfer(VueCallBack vueCallBack1) {
        int i=posMachineMapper.doTransfer(vueCallBack1);
        return i;
    }

    @Override
    public int doTransferEntry(VueCallBack vueCallBack1) {
        int i=posMachineMapper.doTransferEntry(vueCallBack1);
        return i;
    }

    @Override
    public List<BizPosBrandType> getPosBrandList() {
        return posMachineMapper.getPosBrandList();
    }

    @Override
    @Transactional
    public boolean posMachineSftBind(ShengFuTongTradeDTO shengFuTongTradeDTO) {
        String jsonExtData = shengFuTongTradeDTO.getDataJson();
        SftBindDTO sftBindDTO=new SftBindDTO();
        if (StringUtils.isNotBlank(jsonExtData) && jsonExtData.startsWith("{") && jsonExtData.endsWith("}"))  {
            //转json对象
            JSONObject json = JSON.parseObject(jsonExtData);
            Long l= Long.valueOf(json.getString("bindDate"));
            Date date=new Date();
            date.setTime(l);
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String bindDate=simpleDateFormat.format(date);
            sftBindDTO.setBindDate(bindDate);//绑定时间
            sftBindDTO.setIdCardNoMask(json.getString("idCardNoMask"));//商户身份证号掩码
            sftBindDTO.setMerchantId(json.getString("merchantId"));//盛付通商户号
            sftBindDTO.setMerchantName(json.getString("merchantName"));//商户名称
            sftBindDTO.setMerchantPhoneNoMask(json.getString("merchantPhoneNoMask"));//商户手机号掩码
            sftBindDTO.setSn(json.getString("sn"));//sn号
            sftBindDTO.setTerminalId(json.getString("terminalId"));//逻辑终端号
            try {
                sftBindDTO.setCreateTime(DateUtils.getTime(json.getString("createTime")));
            } catch (Exception e) {
                e.printStackTrace();
            }
            sftBindDTO.setDirectPromoterId(json.getString("promoterId"));
            sftBindDTO.setDirectPromoterId(json.getString("directPromoterId"));
            BizPosMachineStatusRecords psr= posMachineMapper.getStfBySn(sftBindDTO.getSn());//查询设备是否被绑定
            if(psr==null){
                boolean b=posMachineMapper.saveSftBind(sftBindDTO);
                return b;
            } else if(psr.getRecordsType().equals("1")){//绑定状态
                return false;
            }
        }
        return false;
    }

    @Override
    @Transactional
    public int posMachineSftActiv(ShengFuTongTradeDTO shengFuTongTradeDTO) {
        String jsonExtData = shengFuTongTradeDTO.getDataJson();
        SftActivDTO sftActivDTO= new SftActivDTO();
        LocalDateTime localDateTime = LocalDateTime.now();
        if (StringUtils.isNotBlank(jsonExtData) && jsonExtData.startsWith("{") && jsonExtData.endsWith("}"))  {
            //转json对象
            JSONObject json = JSON.parseObject(jsonExtData);
            System.out.println(json);
            sftActivDTO.setMerchantId(json.getString("merchantId"));//盛付通商户号
            sftActivDTO.setPromoterId(json.getString("promoterId"));//代理商商户号
            sftActivDTO.setSn(json.getString("sn"));//sn号
            sftActivDTO.setTradeNo(json.getString("tradeNo"));//交易单号
            Long l= Long.valueOf(json.getString("tradeDate"));
            Date date=new Date();
            date.setTime(l);
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String tradeDate=simpleDateFormat.format(date);
            sftActivDTO.setTradeDate(tradeDate);//交易时间
            sftActivDTO.setCashPledgeAmt(json.getString("cashPledgeAmt"));//押金金额，单位元
        }

        BizPosMachineStatusRecords psr= posMachineMapper.getStfBySn(sftActivDTO.getSn());//查询设备是否被绑定
        // 通过设备号获得商户信息
        BizPosMachine posMachine = getPosMachineBySnCode(psr.getSnCode());
        // 获得pos机类型   查看他的返现  返积分情况
        String posTypeId = posMachine.getPosType();
        // 处理一下数据库为null或者""的情况
        posTypeId = StringUtils.isEmpty(posTypeId) || posTypeId==null ?"1":posTypeId;
        BizPosType posType = posTypeService.getPosTypeById(Long.parseLong(posTypeId));
        Double returnMoney = 120.00; // 默认返现金额
        Double returnTaxation = 0.09;// 默认税点
        Long returnIntegral = 120L; // 通用积分
        // 获得政策中的返现金额
        if(posType!=null){
            returnMoney = posType.getReturnMoney().doubleValue();
            returnTaxation = posType.getTaxation().doubleValue();
            returnIntegral = posType.getReturnIntegral();
        }
        //向商户账单表中插入数据
        //--------------------- 插入账单  返现 1--------------------------
        // 更新pos机器状态
        int i=0;
        if(psr.getRecordsType().equals("1")){
            i= posMachineMapper.updateBySn(sftActivDTO);
        }
        Long merId = posMachine.getMerchId();
        // 获得商户
        BizMerchant bizMerchant = iBizMerchantService.getMerchantByMerchId(merId);
        // 获得用户id
        Long userId = bizMerchant.getUserId();
        // 返现发消息
        // String fanXianMess = "返现："+returnMoney*(1-returnTaxation)+"元";
        String fanXianMess = "返现："+returnMoney+"元";
        BizMessageRecords fanXianMessageRecords = new BizMessageRecords();
        fanXianMessageRecords.setMsgContent(fanXianMess);// 消息内容
        fanXianMessageRecords.setMsgType(2); // 消息类型  返现   机具激活返现
        fanXianMessageRecords.setReadStatus(0); // 消息未读
        fanXianMessageRecords.setAdviceType(1); // 业务消息
        webSocketServer.sendInfo(userId,fanXianMessageRecords);// 发送消息
        // 账单信息
        BizMerchBill merchBill = new BizMerchBill();
        BizMerchant merchant = iBizMerchantService.getMerchantByMerchId(merId);
        merchBill.setMerchId(posMachine.getMerchId());//POS机器的主人
        merchBill.setMerchName(psr.getName()); // 名称
        merchBill.setPosType(posMachine.getPosType()); // 设备类型
        merchBill.setPosCode(posMachine.getPosCode()); // 设备编号
        merchBill.setBillType("1"); // 账单类型  返现
        // BigDecimal amount = new BigDecimal(returnMoney*(1-returnTaxation));
        BigDecimal amount = new BigDecimal(returnMoney);
        merchBill.setAmount(amount.setScale(2,BigDecimal.ROUND_HALF_UP));// 返现金额  四射侮辱
//        merchBill.setPolicyId(psr.getPolicyId());//正常id  默认设置成1001
        merchBill.setBillDate(DateUtils.localeDateTime2String(localDateTime, Constants.DATETIME_FORMATTER)); // 账单日期
        BigDecimal taxation = new BigDecimal(returnMoney*returnTaxation);
        merchBill.setTaxation(taxation.setScale(2,BigDecimal.ROUND_HALF_UP)); // 税点
        merchBill.setMsgId(fanXianMessageRecords.getMsgId());
        // 保存账单
        bizMerchBillService.saveOrUpdate(merchBill);
        Long merchId = posMachine.getMerchId();
        // 返积分发消息
        String jiFenMess = "返积分："+returnIntegral;
        BizMessageRecords jiFenMessageRecords = new BizMessageRecords();
        jiFenMessageRecords.setMsgContent(jiFenMess);// 消息内容
        jiFenMessageRecords.setMsgType(8); // 消息类型  返积分
        jiFenMessageRecords.setReadStatus(0);// 消息未读
        jiFenMessageRecords.setAdviceType(1); // 业务消息
        webSocketServer.sendInfo(userId,jiFenMessageRecords);// 发送消息
        //向商户积分表中插入数据
        //--------------------- 插入积分明细   激活机具--------------------------
        BizMerchIntegral merchIntegral = new BizMerchIntegral();
        merchIntegral.setMerchId(merchId);
        merchIntegral.setPosCode(posMachine.getPosCode());
        merchIntegral.setIntegralType("激活机具");
        merchIntegral.setValue(returnIntegral);
        merchIntegral.setTransType("1");//收入  支出2
        merchIntegral.setMsgId(jiFenMessageRecords.getMsgId());// 设置消息id
        // merchIntegral.setOrderId(UUID.randomUUID().toString().replaceAll("-","")); //订单编号
        merchIntegralService.saveOrUpdate(merchIntegral);
        //---------------------  更新钱包   ----------------------------
        // 1-通过user_id获取钱包
        BizWallet wallet = walletService.getMyWalletByUserId(userId);
        // 更新数据
        String secProfitAmount = wallet.getProfitAmount();//获得结算账户余额
        String secRewardAmount = wallet.getRewardAmount();// 获得激活奖励账户
        String secIntegral = wallet.getIntegral(); // 通用积分
        String key = wallet.getSecretKey();// 获得key
        // 解密数据
        String profitAmountStr = DESHelperUtil.decrypt(key,secProfitAmount);
        String rewardAmountStr = DESHelperUtil.decrypt(key,secRewardAmount);
        String integralStr = DESHelperUtil.decrypt(key,secIntegral);
        // 转换成BigDecimal类型
        BigDecimal profitAmount = new BigDecimal(profitAmountStr);
        BigDecimal rewardAmount = new BigDecimal(rewardAmountStr);
        // 把钱加入到结算账户中
        //profitAmount = profitAmount.add(BigDecimal.valueOf(returnMoney*(1-returnTaxation)));
        // 把钱加入到激活奖励账户中
        rewardAmount = rewardAmount.add(BigDecimal.valueOf(returnMoney));
        BigDecimal walletAmount = profitAmount.add(rewardAmount);
        Long integral = Long.parseLong(integralStr);
        integral = integral+returnIntegral;// 通用积分
        // 加密
        String profitAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(profitAmount));
        String rewardAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(rewardAmount));
        String walletAmountMoneyStr = DESHelperUtil.encrypt(key, BigDecimalUtil.getString(walletAmount));
        String integralMoneyStr = DESHelperUtil.encrypt(key,String.valueOf(integral));
        wallet.setProfitAmount(profitAmountMoneyStr);
        wallet.setRewardAmount(rewardAmountMoneyStr);
        wallet.setWalletAmount(walletAmountMoneyStr);
        wallet.setIntegral(integralMoneyStr);
        wallet.setSecretKey(key);
        // 保存钱包信息
        walletService.saveOrUpdate(wallet);
        // 保存设备与伙伴团队的对应信息
        bizPosMachineStatusRecordsService.generatePosMerchantRelatedProcedure(psr.getSnCode(),merchId);
            return i;
    }

    @Override
    @Transactional
    public int posMachineSftSettle(ShengFuTongTradeDTO shengFuTongTradeDTO) {
        String jsonExtData = shengFuTongTradeDTO.getDataJson();
        SftSettleDTO sftSettleDTO=new SftSettleDTO();
        if (StringUtils.isNotBlank(jsonExtData) && jsonExtData.startsWith("{") && jsonExtData.endsWith("}"))  {
            //转json对象
            JSONObject json = JSON.parseObject(jsonExtData);
            System.out.println(json);
            sftSettleDTO.setMerchantId(json.getString("merchantId"));
            sftSettleDTO.setOrderId(json.getString("orderId"));
            sftSettleDTO.setTxnTime(json.getString("txnTime"));
//                BizMerchTransactions merchTransaction=bizMerchTransactionsMapper.selectTransactionByOrderId(sftSettleDTO);
//                String cardType=merchTransaction.getCardType();
            sftSettleDTO.setStlAmt(json.getString("stlAmt"));
            sftSettleDTO.setFee(json.getString("fee"));
            sftSettleDTO.setStlBillNo(json.getString("stlBillNo"));
        }
        //更新交易记录discount_rate_flag字段
        int i=bizMerchTransactionsMapper.updateTransactionByOrderId(sftSettleDTO);
        return i;
    }


    @Override
    @Transactional
    public int posMachineSftDeposit(ShengFuTongTradeDTO shengFuTongTradeDTO) {
        String jsonExtData = shengFuTongTradeDTO.getDataJson();
        int i=0;
        if (StringUtils.isNotBlank(jsonExtData) && jsonExtData.startsWith("{") && jsonExtData.endsWith("}")){
            //转json对象
            JSONObject json = JSON.parseObject(jsonExtData);
            System.out.println(json);
            String orderNo=json.getString("orderNo");//订单号
            BigDecimal withdarwFee=json.getBigDecimal("withdarwFee");
            BigDecimal bigDecimal = new BigDecimal("3");
            //查询交易记录
            BizMerchTransactions merchTransaction=bizMerchTransactionsMapper.selectTransactionByInnerMerchCode(orderNo);
            //判断手续费为3并且卡类型为0001
            if(withdarwFee.compareTo(bigDecimal)==0 && merchTransaction.getCardType().equals("0001")){
                //更新交易类型为0（刷卡）
                i=  bizMerchTransactionsMapper.updateTransactionByFee(merchTransaction.getInnerMerchCode());
                return i;
            }else{
                return 1;
            }
        }
        return i;
    }

    @Override
    public BizPosMachine selectPosBySnCode(String snCode) {
        LambdaQueryWrapper<BizPosMachine> lq = Wrappers.lambdaQuery();
        lq.eq(BizPosMachine::getPosCode,snCode);
        return this.getOne(lq);
    }

    /**
     * 查询终端费率Id
     * @return
     */
    @Override
    public List<BizPosErminalRate> selectPosErminalRate() {
        return posMachineMapper.selectPosErminalRate();
    }

    @Override
    public String importBizPos(List<BizPosMachine> userList, boolean updateSupport) {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new CustomException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (BizPosMachine user : userList)
        {
            try
            {
                // 验证是否存在这个用户
                //SysUser u = userMapper.selectUserByUserName(user.getUserName());
                BizPosMachine u = bizPosMachineMapper.selectPosMachineBySn(user.getPosCode());
                if (StringUtils.isNull(u))
                {
                    bizPosMachineMapper.insertPosMachine(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getPosCode() + " 导入成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getPosCode() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getPosCode() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public void updatePosMachine(String snCode) {
        bizPosMachineMapper.updatePosMachine(snCode);
        bizPosMachineMapper.generateAllPosMerchantRelatedProcedure();// 运行函数
    }

    @Override
    public void updatePosPosMachine(String snCode) {
        bizPosMachineMapper.updatePosPosMachine(snCode);
        bizPosMachineMapper.generateAllPosMerchantRelatedProcedure();// 运行函数
    }

    @Override
    public void generateAllPosMerchParentRelated() {
        bizMerchantMapper.generateAllPosMerchParentRelated();
    }

    @Override
    public String getVar() {
        return bizPosMachineMapper.getVar();
    }

    public List<BizPosMachine> selectBizPosMachineAllList() {
        return bizPosMachineMapper.selectBizPosMachineAllList();
    }
    @Override
    public void insertPosMachine(String fictitiousSnCode, Long merchId) {
        BizPosMachine bizPosMachine =new BizPosMachine();
        bizPosMachine.setPosName("虚拟");
        bizPosMachine.setPosCode(fictitiousSnCode);
        bizPosMachine.setPosType("4");
        bizPosMachine.setPosActivateStatus("2");
        bizPosMachine.setPosBindTime(new Date());
        bizPosMachine.setPosDeposit(new BigDecimal("0.00"));
        bizPosMachine.setPosCashback(new BigDecimal("0.00"));
        bizPosMachine.setMerchId(merchId);
        bizPosMachine.setCreateBy(0L);
        bizPosMachine.setCreateTime(new Date());
        bizPosMachine.setUpdateBy(0L);
        bizPosMachine.setUpdateTime(new Date());
        bizPosMachineMapper.insertPosMachineFictitious(bizPosMachine);
    }

    @Override
    public String selectMerchantEntryPhone(Long id) {
        return bizPosMachineMapper.selectMerchantEntryPhone(id);
    }

    @Override
    public void updatebizPosMachineMerchIdAndStatus(String sn, Long merchId) {
        bizPosMachineMapper.updatebizPosMachineMerchIdAndStatus(sn,merchId);
    }

    @Override
    public List<BizMerchantEntry> selectEntryAll() {
        List<BizMerchantEntry> bizMerchantEntry= bizPosMachineMapper.selectEntryAll();
        return bizMerchantEntry;
    }

    @Override
    public List<BizProfitDeatail> selectfenrun(String uuid) {
        List<BizProfitDeatail> bizProfitDeatails= bizPosMachineMapper.selectfenrun(uuid);
        return bizProfitDeatails;
    }

    @Override
    public List<BizPosMachine> selectBizPosMachinesSn() {
        List<BizPosMachine> bizPosMachines= bizPosMachineMapper.selectBizPosMachinesSn();
        return bizPosMachines;
    }

    @Override
    public int updateBizPosMachinesTerminalNo(BizPosMachine bizPosMachine11) {
        int bizPosMachines= bizPosMachineMapper.updateBizPosMachinesTerminalNo(bizPosMachine11);
        return bizPosMachines;
    }

    @Override
    public List<SynchronizationDataDTO> selectUuidIsNull() {
        Date date=new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        List<SynchronizationDataDTO> synchronizationDataDTOS= bizPosMachineMapper.selectUuidIsNull("2022-03-12");
        return synchronizationDataDTOS;
    }

    @Override
    public Long selectParentId(Long merchId) {
        return bizPosMachineMapper.selectParentId(merchId);
    }

    @Override
    public List<BizPosMachine> timerGetAllPos() {
        return bizPosMachineMapper.timerGetAllPos();
    }
    @Override
    public List<BizHaofan> selzyf() {
        return bizPosMachineMapper.selzyf();
    }

    @Override
    public BizRenRunSubsidiesDTO selectBizRenRunSubsidiesKeyWord(Long merchId)
    {
        return posMachineMapper.selectBizRenRunSubsidiesKeyWord(merchId);
    }

    @Override
    @Transactional
    public int selectIsTransfer(WalletNewDTO bizPosMachine) {
        return posMachineMapper.selectIsTransfer(bizPosMachine);
    }

    @Override
    @Transactional
    public BizPosMachine selectPosMachineType(WalletNewDTO bizPosMachine) {
        return posMachineMapper.selectPosMachineType(bizPosMachine);
    }


    @Override
    public BizPosMachine selmerchId1(String posCode) {
        BizPosMachine list = posMachineMapper.selmerchId1(posCode);
        return list;
    }

    @Override
    public Long seluserid1(Long merchId1) {
        Long list = posMachineMapper.seluserid1(merchId1);
        return list;
    }

    @Override
    public Long seluserid(Long merchId) {
        Long list = posMachineMapper.seluserid(merchId);
        return list;
    }

    @Override
    @Transactional
    public int updateMerchantsEquipmentVue(Long merchId, String posCode) {
        int list = posMachineMapper.updateMerchantsEquipmentVue(merchId, posCode);
        posMachineMapper.generateAllPosMerchantRelated();
        return list;
    }

    @Override
    @Transactional
    public Long selectMerchantsEntry(String posCode) {
        Long list = posMachineMapper.selectMerchantsEntry(posCode);
        return list;
    }
    @Override
    @Transactional
    public int updateMerchantsEntry(Long merchId, Long id) {
        int list = posMachineMapper.updateMerchantsEntry(merchId, id);
        return list;
    }

    @Override
    public void updatePosPosMachineActivateStatusBySn(String posCode) {
        bizPosMachineMapper.updatePosPosMachineActivateStatusNew(posCode);
    }

    @Override
    public SignatureDTO selectPosMoneyInfo(String merchantNo) {
        return bizPosMachineMapper.selectPosMoneyInfo(merchantNo);
    }


    @Override
    public List<StorageEquipment> getManufacturer() {
        return bizPosMachineMapper.getManufacturer();
    }

    @Override
    public List<StorageEquipment> getManufacturerModel(Long id) {
        return bizPosMachineMapper.getManufacturerModel(id);
    }

    @Override
    public List<StorageEquipment> getServiceCharge(Long id) {
        return bizPosMachineMapper.getServiceCharge(id);
    }

    @Override
    public StorageEquipment getManufacturerByid(String id) {
        return bizPosMachineMapper.getManufacturerByid(id);
    }

    @Override
    public String getUnitType(String posModel) {
        return bizPosMachineMapper.getUnitType(posModel);
    }

    @Override
    public int updateEquipment(PospPosmachine pospPosmachine) {

        Map<String, String> data = new HashMap<String, String>();
        //查询制造商
        PospPosmachine Posmachine =  posMachineMapper.getPosCodeInfo(pospPosmachine.getPosSn());
        data.put("posName", "1".equals(pospPosmachine.getPosName())?"11" : pospPosmachine.getPosName());
        data.put("posSn", pospPosmachine.getPosSn());
        String  posModel =   posMachineMapper.getUnitType(pospPosmachine.getPosModel());
        data.put("posModel", "1".equals(pospPosmachine.getPosModel()) ? "17":pospPosmachine.getPosModel());
        data.put("posTypeId", pospPosmachine.getPosTypeId());
        data.put("channel", Posmachine.getChannel());
        data.put("userCode", pospPosmachine.getUserCode());
        data.put("createTime", DateUtils.dateFormatString(new Date()));
        data.put("frozenAmount", pospPosmachine.getFrozenAmount().toString());
        data.put("flowAmount", pospPosmachine.getFlowAmount().toString());
        data.put("devImei", pospPosmachine.getDevImei());
        data.put("simDaynum", pospPosmachine.getSimDaynum());
        data.put("simIccid", pospPosmachine.getSimIccid());
        data.put("channel", pospPosmachine.getChannel());
        data.put("agentid", "ANXINFU");
        data.put("fee",pospPosmachine.getFeeId().toString());
        System.out.println("请求参数--》》》》"+ JSONObject.toJSONString(data));
        // String url = "http://192.168.3.109:8083/pos/merchantInfo/updateEquipment";
        String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getEditBizPosMachine(), JSONObject.toJSONString(data));
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject.getInteger("code") == 200){
            BizPosMachine bizPosMachine = new BizPosMachine();
            String posTypeName = posMachineMapper.selectPosType(pospPosmachine.getPosTypeId());
            bizPosMachine.setPosType(pospPosmachine.getPosTypeId());
            bizPosMachine.setPosName(posTypeName);
            bizPosMachine.setPosCode(pospPosmachine.getPosSn());
            bizPosMachine.setDeviceType(posModel);
            bizPosMachine.setModelId(pospPosmachine.getPosModel());
            bizPosMachine.setSimAmt(pospPosmachine.getFlowAmount().toString());
            bizPosMachine.setSimDaynum(pospPosmachine.getSimDaynum());
            bizPosMachine.setManufacturersId(pospPosmachine.getPosName());
            bizPosMachine.setSimIccid(pospPosmachine.getSimIccid());
            bizPosMachine.setDevImei(pospPosmachine.getDevImei());
            bizPosMachine.setVar5(pospPosmachine.getFrozenAmount().toString());  //流量费执行时间
            bizPosMachine.setChannel(pospPosmachine.getChannel());
            bizPosMachine.setCustomerCashBackId(pospPosmachine.getTemp3());
            bizPosMachine.setTemp1(pospPosmachine.getTemp1());
            bizPosMachine.setTemp2(pospPosmachine.getTemp2());
            bizPosMachine.setFee(String.valueOf(pospPosmachine.getFeeId()));
            return posMachineMapper.updatePosPMachaine(bizPosMachine);
        }
        return 0;
    }


    @Override
    public AjaxResult jlUpdateDep(PospPosmachine pospPosmachine) {
        Map<String, String> data = new HashMap<String, String>();
        data.put("deviceSn", pospPosmachine.getPosSn());
        data.put("deposit", pospPosmachine.getFrozenAmount().toString());

        BizPosMachine bizPosMachine1 = posMachineMapper.selectPosMachineBySn(pospPosmachine.getPosSn());
        // 传一个 机构id   这是嘉联机构代码
        SysUser sysUser = sysUserMapper.selectUserByMerchId(bizPosMachine1.getMerchId());
        // 查询出哪个机构的
        data.put("agentId",sysUser.getJlAgent());
        data.put("agentid", "ANXINFU");
        System.out.println("请求参数--》》》》"+ JSONObject.toJSONString(data));
        // String url = "http://192.168.3.109:8083/pos/merchantInfo/updateEquipment";
        String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getJlPreSetRates(), JSONObject.toJSONString(data));
        JSONObject jsonObject = JSONObject.parseObject(result);
        if ("00".equals(jsonObject.getString("ret_code"))) {
            BizPosMachine bizPosMachine = new BizPosMachine();
            bizPosMachine.setPosCode(pospPosmachine.getPosSn());
            bizPosMachine.setVar5(pospPosmachine.getFrozenAmount().toString());  //流量费执行时间
            posMachineMapper.updatePosPMachaine(bizPosMachine);
            return AjaxResult.success();
        }else {
            return AjaxResult.error(jsonObject.getString("ret_msg"));
        }

    }

    @Override
    public PospPosmachine getPosCodeInfo(String  posCode) {
        return posMachineMapper.getPosCodeInfo(posCode);
    }

    @Override
    public int doTransfers(VueCallBack vueCallBack1) {

        return posMachineMapper.doTransfers(vueCallBack1);
    }
    private String agentid(){
        SysUser sysUserman = SecurityUtils.getLoginUser().getUser();
        String suffix=bizMerchantInfoMapper.getSuffix(sysUserman.getUserId());
        return bizMerchantInfoMapper.getAgentId(suffix);
    }


    @Override
    public AjaxResult allocationSn(AllocationRelation allocationRelation) {
        List<Long> posIdsList = allocationRelation.getPosIds();
        if(posIdsList.size() <= 0){
            return AjaxResult.success("未勾选设备");
        }
        List<String> snList = posMachineMapper.getSnListByIds(posIdsList);
        BizPosMachine bizPosMachine = posMachineMapper.selectPosMachineBySn(snList.get(0));
        SysUser sysUser = iSysUserService.selectUserById(allocationRelation.getUserId());
        BizTransferRecords bizTransferRecords = new BizTransferRecords();
        bizTransferRecords.setType("APP划拨");
        bizTransferRecords.setReceiver(sysUser.getNickName()+"-"+sysUser.getPhonenumber());
        String detailId = UUID.randomUUID().toString().replace("-","").toUpperCase();
        bizTransferRecords.setDetailId(detailId);
        bizTransferRecords.setTransferTime(new Date());
        bizTransferRecords.setChannel(bizPosMachine.getChannel());
        BizMerchant bizMerchant = iBizMerchantService.getMerchantByMerchId(bizPosMachine.getMerchId());
        bizTransferRecords.setUserId(bizMerchant.getUserId());
        posMachineMapper.insertIntoTrscords(bizTransferRecords);
        allocationRelation.setDetailId(detailId);
        for(String sn : snList){
            allocationRelation.setPosSn(sn);
            executeAllocationSn(allocationRelation);
        }
        return AjaxResult.success("划拨完成");
    }



    @Transactional
    public void executeAllocationSn(AllocationRelation allocationRelation) {
        allocationRelation.setId(null);
        String sn = allocationRelation.getPosSn();
        BizPosMachine bizPosMachine = iBizPosMachineService.getPosMachineBySnCode(sn);
        // 划拨人的merchId 是当前设备的所属代理
        BizMerchant bizMerchant = iBizMerchantService.getMerchantByUserId(allocationRelation.getUserId());
        Long merchId = bizMerchant.getMerchId();//// 接收人
        // 根据模板id找到对用模板
        Long settlementId = allocationRelation.getSettlementId();
        SettlementRateTemplate settlementRateTemplate = iSettlementRateTemplateService.getById(settlementId);
        //查看是否第一次划拨改机具  查看关系表是否有改设备划拨数据
        List<AllocationRelation> oldAllocationRelation = posMachineMapper.getAllocationRelationBySn(sn);
        //  流量费 list
        List<Map<String,Object>> flowList = allocationRelation.getFlowList();
        // 存储划拨记录
        if(oldAllocationRelation.size() == 0){// 第一次划拨
            AllocationRelation allocationRelationParent = new AllocationRelation();
            allocationRelationParent.setPosSn(sn);
            allocationRelationParent.setSettlementRate(new BigDecimal(0.00505));
            allocationRelationParent.setQrCodeRate(new BigDecimal(0.0038));
            allocationRelationParent.setDebitFee(new BigDecimal(0.0060));
            allocationRelationParent.setDebitCap(new BigDecimal(42));
            allocationRelationParent.setD0Fee(new BigDecimal(3).subtract(settlementRateTemplate.getD0Fee()).setScale(2,BigDecimal.ROUND_DOWN));
            allocationRelationParent.setMerchId(bizPosMachine.getMerchId());
            BizMerchant bizMerchantParent = bizMerchantMapper.selectInfoByMerchId(bizPosMachine.getMerchId());
            allocationRelationParent.setMerchName(bizMerchantParent.getMerchName());
            allocationRelationParent.setCreateTime(new Date());
            allocationRelationParent.setLevel(1l);
            allocationRelationParent.setSettlementId(allocationRelation.getSettlementId());
            allocationRelationParent.setCommission(String.valueOf(new BigDecimal(100).subtract(new BigDecimal(Double.parseDouble(settlementRateTemplate.getAdjustmentShare())))));
            allocationRelationParent.setServiceFee(new BigDecimal(bizPosMachine.getVar5())
                    .subtract(allocationRelation.getServiceFee()).setScale(2,BigDecimal.ROUND_DOWN));
//            allocationRelationParent.setSimFee(new BigDecimal(bizPosMachine.getSimAmt())
//                    .subtract(allocationRelation.getSimFee()).setScale(2,BigDecimal.ROUND_DOWN));
//            allocationRelationParent.setSimFeeLast(new BigDecimal(bizPosMachine.getSimAmt())
//                    .subtract(allocationRelation.getSimFeeLast()).setScale(2,BigDecimal.ROUND_DOWN));
            allocationRelationParent.setVip(new BigDecimal(39).subtract(allocationRelation.getVip()));
            allocationRelationParent.setStandardCashback(new BigDecimal(100));
            for(Map<String,Object> map : flowList ){
                if("fortyEight".equals(map.get("id"))){
                    allocationRelationParent.setFortyEight(new BigDecimal(48).subtract(new BigDecimal(map.get("value").toString())).setScale(2,BigDecimal.ROUND_DOWN));
                    continue;
                }
                if("fiftyEight".equals(map.get("id"))){
                    allocationRelationParent.setFiftyEight(new BigDecimal(58).subtract(new BigDecimal(map.get("value").toString())).setScale(2,BigDecimal.ROUND_DOWN));
                    continue;
                }
                if("sixty".equals(map.get("id"))){
                    allocationRelationParent.setSixty(new BigDecimal(60).subtract(new BigDecimal(map.get("value").toString())).setScale(2,BigDecimal.ROUND_DOWN));
                    continue;
                }
                if("sixtyEight".equals(map.get("id"))){
                    allocationRelationParent.setSixtyEight(new BigDecimal(68).subtract(new BigDecimal(map.get("value").toString())).setScale(2,BigDecimal.ROUND_DOWN));
                    continue;
                }
                if("seventySeven".equals(map.get("id"))){
                    allocationRelationParent.setSeventySeven(new BigDecimal(77).subtract(new BigDecimal(map.get("value").toString())).setScale(2,BigDecimal.ROUND_DOWN));
                    continue;
                }
                if("seventyEight".equals(map.get("id"))){
                    allocationRelationParent.setSeventyEight(new BigDecimal(78).subtract(new BigDecimal(map.get("value").toString())).setScale(2,BigDecimal.ROUND_DOWN));
                    continue;
                }
                if("eightyEight".equals(map.get("id"))){
                    allocationRelationParent.setEightyEight(new BigDecimal(88).subtract(new BigDecimal(map.get("value").toString())).setScale(2,BigDecimal.ROUND_DOWN));
                    continue;
                }
                if("ninetyEight".equals(map.get("id"))){
                    allocationRelationParent.setNinetyEight(new BigDecimal(98).subtract(new BigDecimal(map.get("value").toString())).setScale(2,BigDecimal.ROUND_DOWN));
                    continue;
                }
                if("ninetyNine".equals(map.get("id"))){
                    allocationRelationParent.setNinetyNine(new BigDecimal(99).subtract(new BigDecimal(map.get("value").toString())).setScale(2,BigDecimal.ROUND_DOWN));
                }
            }
//            //流量费
//            allocationRelationParent.setFiftyEight(new BigDecimal(58).subtract(allocationRelation.getFiftyEight()).setScale(2,BigDecimal.ROUND_DOWN));
//            allocationRelationParent.setSixty(new BigDecimal(60).subtract(allocationRelation.getSixty()).setScale(2,BigDecimal.ROUND_DOWN));
//            allocationRelationParent.setSixtyEight(new BigDecimal(68).subtract(allocationRelation.getSixtyEight()).setScale(2,BigDecimal.ROUND_DOWN));
//            allocationRelationParent.setSeventySeven(new BigDecimal(77).subtract(allocationRelation.getSeventySeven()).setScale(2,BigDecimal.ROUND_DOWN));
//            allocationRelationParent.setSeventyEight(new BigDecimal(78).subtract(allocationRelation.getSeventyEight()).setScale(2,BigDecimal.ROUND_DOWN));
//            allocationRelationParent.setEightyEight(new BigDecimal(88).subtract(allocationRelation.getEightyEight()).setScale(2,BigDecimal.ROUND_DOWN));
//            allocationRelationParent.setNinetyEight(new BigDecimal(98).subtract(allocationRelation.getNinetyEight()).setScale(2,BigDecimal.ROUND_DOWN));
//            allocationRelationParent.setNinetyNine(new BigDecimal(99).subtract(allocationRelation.getNinetyNine()).setScale(2,BigDecimal.ROUND_DOWN));
            iAllocationRelationService.saveOrUpdate(allocationRelationParent);
            allocationRelation.setLevel(2l);
            allocationRelation.setCommission(settlementRateTemplate.getAdjustmentShare());
        }else{//  非第一次划拨
            allocationRelation.setLevel(Long.parseLong(String.valueOf(oldAllocationRelation.size()+1)));
            // 找到当前代理的划拨记录 更新d0 流量费 押金
            AllocationRelation allocationRelationNow = iAllocationRelationService.selectInfoBySnAndMerchId(sn,bizPosMachine.getMerchId());
            allocationRelationNow.setD0Fee(allocationRelationNow.getD0Fee().subtract(settlementRateTemplate.getD0Fee()).setScale(2,BigDecimal.ROUND_DOWN));
            allocationRelationNow.setServiceFee(allocationRelationNow.getServiceFee().subtract(allocationRelation.getServiceFee()).setScale(2,BigDecimal.ROUND_DOWN));
//            allocationRelationNow.setSimFee(allocationRelationNow.getSimFee().subtract(allocationRelation.getSimFee()).setScale(2,BigDecimal.ROUND_DOWN));
//            allocationRelationNow.setSimFeeLast(allocationRelationNow.getSimFeeLast().subtract(allocationRelation.getSimFeeLast()).setScale(2,BigDecimal.ROUND_DOWN));
//            allocationRelationNow.setDebitFee(allocationRelationNow.getDebitFee().subtract(settlementRateTemplate.getDebitFee()).setScale(2,BigDecimal.ROUND_DOWN));
            allocationRelationNow.setDebitCap(allocationRelationNow.getDebitCap().subtract(settlementRateTemplate.getDebitCap()).setScale(2,BigDecimal.ROUND_DOWN));
            allocationRelationNow.setCommission(String.valueOf(new BigDecimal(allocationRelationNow.getCommission()).subtract(new BigDecimal(Double.parseDouble(settlementRateTemplate.getAdjustmentShare())))));
//            allocationRelationNow.setStandardCashback(allocationRelationNow.getStandardCashback().subtract(allocationRelation.getStandardCashback()).setScale(2,BigDecimal.ROUND_DOWN));
            allocationRelationNow.setVip(allocationRelationNow.getVip().subtract(allocationRelation.getVip()));
            for(Map<String,Object> map : flowList ){
                if("fortyEight".equals(map.get("id"))){
                    allocationRelationNow.setFortyEight(allocationRelationNow.getFortyEight().subtract(new BigDecimal(map.get("value").toString())).setScale(2,BigDecimal.ROUND_DOWN));
                    continue;
                }
                if("fiftyEight".equals(map.get("id"))){
                    allocationRelationNow.setFiftyEight(allocationRelationNow.getFiftyEight().subtract(new BigDecimal(map.get("value").toString())).setScale(2,BigDecimal.ROUND_DOWN));
                    continue;
                }
                if("sixty".equals(map.get("id"))){
                    allocationRelationNow.setSixty(allocationRelationNow.getSixty().subtract(new BigDecimal(map.get("value").toString())).setScale(2,BigDecimal.ROUND_DOWN));
                    continue;
                }
                if("sixtyEight".equals(map.get("id"))){
                    allocationRelationNow.setSixtyEight(allocationRelationNow.getSixtyEight().subtract(new BigDecimal(map.get("value").toString())).setScale(2,BigDecimal.ROUND_DOWN));
                    continue;
                }
                if("seventySeven".equals(map.get("id"))){
                    allocationRelationNow.setSeventySeven(allocationRelationNow.getSeventySeven().subtract(new BigDecimal(map.get("value").toString())).setScale(2,BigDecimal.ROUND_DOWN));
                    continue;
                }
                if("seventyEight".equals(map.get("id"))){
                    allocationRelationNow.setSeventyEight(allocationRelationNow.getSeventyEight().subtract(new BigDecimal(map.get("value").toString())).setScale(2,BigDecimal.ROUND_DOWN));
                    continue;
                }
                if("eightyEight".equals(map.get("id"))){
                    allocationRelationNow.setEightyEight(allocationRelationNow.getEightyEight().subtract(new BigDecimal(map.get("value").toString())).setScale(2,BigDecimal.ROUND_DOWN));
                    continue;
                }
                if("ninetyEight".equals(map.get("id"))){
                    allocationRelationNow.setNinetyEight(allocationRelationNow.getNinetyEight().subtract(new BigDecimal(map.get("value").toString())).setScale(2,BigDecimal.ROUND_DOWN));
                    continue;
                }
                if("ninetyNine".equals(map.get("id"))){
                    allocationRelationNow.setNinetyNine(allocationRelationNow.getNinetyNine().subtract(new BigDecimal(map.get("value").toString())).setScale(2,BigDecimal.ROUND_DOWN));
                }
            }
            //流量费
//            allocationRelationNow.setFortyEight(allocationRelationNow.getFortyEight().subtract(allocationRelation.getFortyEight()).setScale(2,BigDecimal.ROUND_DOWN));
//            allocationRelationNow.setFiftyEight(allocationRelationNow.getFiftyEight().subtract(allocationRelation.getFiftyEight()).setScale(2,BigDecimal.ROUND_DOWN));
//            allocationRelationNow.setSixty(allocationRelationNow.getSixty().subtract(allocationRelation.getSixty()).setScale(2,BigDecimal.ROUND_DOWN));
//            allocationRelationNow.setSixtyEight(allocationRelationNow.getSixtyEight().subtract(allocationRelation.getSixtyEight()).setScale(2,BigDecimal.ROUND_DOWN));
//            allocationRelationNow.setSeventySeven(allocationRelationNow.getSeventySeven().subtract(allocationRelation.getSeventySeven()).setScale(2,BigDecimal.ROUND_DOWN));
//            allocationRelationNow.setSeventyEight(allocationRelationNow.getSeventyEight().subtract(allocationRelation.getSeventyEight()).setScale(2,BigDecimal.ROUND_DOWN));
//            allocationRelationNow.setEightyEight(allocationRelationNow.getEightyEight().subtract(allocationRelation.getEightyEight()).setScale(2,BigDecimal.ROUND_DOWN));
//            allocationRelationNow.setNinetyEight(allocationRelationNow.getNinetyEight().subtract(allocationRelation.getNinetyEight()).setScale(2,BigDecimal.ROUND_DOWN));
//            allocationRelationNow.setNinetyNine(allocationRelationNow.getNinetyNine().subtract(allocationRelation.getNinetyNine()).setScale(2,BigDecimal.ROUND_DOWN));
            iAllocationRelationService.saveOrUpdate(allocationRelationNow);
        }
        //增加接收设备的代理划拨记录
//        BizMerchant bizMerchant = bizMerchantMapper.selectInfoByMerchId(allocationRelation.getMerchId());
        allocationRelation.setMerchName(bizMerchant.getMerchName());
        allocationRelation.setMerchId(merchId);
        allocationRelation.setSettlementRate(settlementRateTemplate.getCreditRate());
        allocationRelation.setDebitFee(settlementRateTemplate.getDebitFee());
        allocationRelation.setDebitCap(settlementRateTemplate.getDebitCap());
        allocationRelation.setCreateTime(new Date());
        allocationRelation.setQrCodeRate(settlementRateTemplate.getQrCodeRate());
        allocationRelation.setCommission(settlementRateTemplate.getAdjustmentShare());
        allocationRelation.setD0Fee(settlementRateTemplate.getD0Fee());
        allocationRelation.setVip(allocationRelation.getVip());
        for(Map<String,Object> map : flowList ){
            if("fortyEight".equals(map.get("id"))){
                allocationRelation.setFortyEight(new BigDecimal(map.get("value").toString()).setScale(2,BigDecimal.ROUND_DOWN));
                continue;
            }
            if("fiftyEight".equals(map.get("id"))){
                allocationRelation.setFiftyEight(new BigDecimal(map.get("value").toString()).setScale(2,BigDecimal.ROUND_DOWN));
                continue;
            }
            if("sixty".equals(map.get("id"))){
                allocationRelation.setSixty(new BigDecimal(map.get("value").toString()).setScale(2,BigDecimal.ROUND_DOWN));
                continue;
            }
            if("sixtyEight".equals(map.get("id"))){
                allocationRelation.setSixtyEight(new BigDecimal(map.get("value").toString()).setScale(2,BigDecimal.ROUND_DOWN));
                continue;
            }
            if("seventySeven".equals(map.get("id"))){
                allocationRelation.setSeventySeven(new BigDecimal(map.get("value").toString()).setScale(2,BigDecimal.ROUND_DOWN));
                continue;
            }
            if("seventyEight".equals(map.get("id"))){
                allocationRelation.setSeventyEight(new BigDecimal(map.get("value").toString()).setScale(2,BigDecimal.ROUND_DOWN));
                continue;
            }
            if("eightyEight".equals(map.get("id"))){
                allocationRelation.setEightyEight(new BigDecimal(map.get("value").toString()).setScale(2,BigDecimal.ROUND_DOWN));
                continue;
            }
            if("ninetyEight".equals(map.get("id"))){
                allocationRelation.setNinetyEight(new BigDecimal(map.get("value").toString()).setScale(2,BigDecimal.ROUND_DOWN));
                continue;
            }
            if("ninetyNine".equals(map.get("id"))){
                allocationRelation.setNinetyNine(new BigDecimal(map.get("value").toString()).setScale(2,BigDecimal.ROUND_DOWN));
            }
        }
        iAllocationRelationService.saveOrUpdate(allocationRelation);
        // 修改设备的代理信息
        bizPosMachine.setMerchId(merchId);
        iBizPosMachineService.saveOrUpdate(bizPosMachine);
        // 保存划拨明细
        BizTransferRecordsDetail btrd = new BizTransferRecordsDetail();
        btrd.setTransferId(allocationRelation.getDetailId());
        btrd.setSn(sn);
        bizPosMachineMapper.insertIntoTrscordsDetails(btrd);
    }

    //  划拨 数据 验证



    @Override
    public AjaxResult posMachineList(BizPosMachine bizPosMachine) {
        BizMerchant bizMerchant = iBizMerchantService.getMerchantByUserId(bizPosMachine.getUserId());
        bizPosMachine.setMerchId(bizMerchant.getMerchId());
        List<BizPosMachine> bizPosMachineList = posMachineMapper.getPosMachineType(bizPosMachine.getMerchId());
        List<JSONObject> list = new ArrayList<>();
        for(BizPosMachine posMachine : bizPosMachineList ){
            JSONObject jsonObject = new JSONObject();
            //总库存数
            int allCount = posMachineMapper.getAllCount(posMachine.getChannel(),bizPosMachine.getMerchId());
            jsonObject.put("total",allCount);//总数
            //当前库存数 -- 我自己的没绑定的没分的
            int canUseCount = posMachineMapper.getCanUseCount(posMachine.getChannel(),bizPosMachine.getMerchId());
            jsonObject.put("canUsed",canUseCount);
            //已分库存 -- 不包含我自己的  切没绑定
            int noMineCount = posMachineMapper.getNoMineCount(posMachine.getChannel(),bizPosMachine.getMerchId());
            jsonObject.put("team",noMineCount);
            //终端绑定
            int bindCount = posMachineMapper.getBindCount(posMachine.getChannel(),bizPosMachine.getMerchId());
            jsonObject.put("bind",bindCount);//绑定总数
            jsonObject.put("id",posMachine.getChannel());
            BizChannel bizChannel = posMachineMapper.getChannelByChannelId(posMachine.getChannel());
            jsonObject.put("title",bizChannel.getChannelName());
            jsonObject.put("image",bizChannel.getImage());
            list.add(jsonObject);
        }
        return AjaxResult.success("我的机具",list);
    }

    @Override
    public AjaxResult posMachineTransList(PosTerminalDTO posTerminalDTO) {
        Long userId = posTerminalDTO.getUserId();
        BizMerchant bizMerchant = iBizMerchantService.getMerchantByUserId(userId);
        posTerminalDTO.setMerchId(bizMerchant.getMerchId());
        posTerminalDTO.setPageNo((posTerminalDTO.getPageNo() - 1) * posTerminalDTO.getPageSize());
        List<BizPosMachine> bizPosMachineList = posMachineMapper.getPosMachineTransList(posTerminalDTO);
        return AjaxResult.success(String.valueOf(bizPosMachineList.size()),bizPosMachineList);
    }

    @Override
    public AjaxResult posMachineIntervalList(PosTerminalDTO posTerminalDTO) {
        posTerminalDTO.setPosActivateStatus("0");
        List<BizPosMachine> terminalList = iBizPosMachineService.getPosMachinesByInteval(posTerminalDTO);
        return AjaxResult.success(String.valueOf(terminalList.size()),terminalList);
    }


    @Override
    public AjaxResult posMachineIntervalServiceFlow(PosTerminalDTO posTerminalDTO) {
        Long userId = posTerminalDTO.getUserId();
        BizMerchant bizMerchant = iBizMerchantService.getMerchantByUserId(userId);
        posTerminalDTO.setMerchId(bizMerchant.getMerchId());
        List<Long> posIdsList = posTerminalDTO.getPosIds();
        List<String> snList = posMachineMapper.getSnListByIds(posIdsList);
        Double minServiceFee = posMachineMapper.getMinServiceFee(snList,bizMerchant.getMerchId());
        Double defaultMinServiceFee = posMachineMapper.getDefaulltMinServiceFee(snList,bizMerchant.getMerchId());
//        AllocationRelation allocationRelation
//                = posMachineMapper.getAllocationRelationBySnForServiceFlowInterval(posTerminalDTO);
        Double minFlowFee = posMachineMapper.getMinFlowFee(snList,bizMerchant.getMerchId());
        Double defaultMinFlowFee = posMachineMapper.getDefaultMinFlowFee(snList,bizMerchant.getMerchId());
        Double minFlowFeeLast = posMachineMapper.getMinFlowFeeLast(snList,bizMerchant.getMerchId());
        Double minVip = posMachineMapper.getMinVip(snList,bizMerchant.getMerchId());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("serviceFee1", 0);
        jsonObject.put("serviceFee2", minServiceFee == null ? defaultMinServiceFee : minServiceFee);// 暂时给默认值  后期再从设备的类型里取
        jsonObject.put("simFee1", 0);
        jsonObject.put("simFee2", minFlowFee == null ? defaultMinFlowFee : minFlowFee);// 暂时给默认值  后期再从设备的类型里取
        jsonObject.put("simFeeLast1", 0);
        jsonObject.put("simFeeLast2", minFlowFeeLast == null ? defaultMinFlowFee : minFlowFeeLast);// 暂时给默认值  后期再从设备的类型里取
        jsonObject.put("minVip1", 0);
        jsonObject.put("minVip2", minVip == null ? "39" : minVip);// 暂时给默认值  后期再从设备的类型里取
        List<JSONObject> flowFeeList = new ArrayList<>();
        // 流量费 们~
        JSONObject fortyEight = new JSONObject();
        fortyEight.put("name","sim返现(48元)");
        fortyEight.put("id","fortyEight");
        fortyEight.put("flowFee",bizMerchant.getMerchId() == 2L?48:posMachineMapper.getMinEachFlowFee("forty_eight",snList,bizMerchant.getMerchId()));
        flowFeeList.add(fortyEight);

        JSONObject fiftyEight = new JSONObject();
        fiftyEight.put("name","sim返现(58元)");
        fiftyEight.put("id","fiftyEight");
        fiftyEight.put("flowFee",bizMerchant.getMerchId() == 2L?58:posMachineMapper.getMinEachFlowFee("fifty_eight",snList,bizMerchant.getMerchId()));
        flowFeeList.add(fiftyEight);

        JSONObject sixty = new JSONObject();
        sixty.put("name","sim返现(60元)");
        sixty.put("id","sixty");
        sixty.put("flowFee",bizMerchant.getMerchId() == 2L?60:posMachineMapper.getMinEachFlowFee("sixty",snList,bizMerchant.getMerchId()));
        flowFeeList.add(sixty);

        JSONObject sixtyEight = new JSONObject();
        sixtyEight.put("name","sim返现(68元)");
        sixtyEight.put("id","sixtyEight");
        sixtyEight.put("flowFee",bizMerchant.getMerchId() == 2L?68:posMachineMapper.getMinEachFlowFee("sixty_eight",snList,bizMerchant.getMerchId()));
        flowFeeList.add(sixtyEight);

        JSONObject seventySeven = new JSONObject();
        seventySeven.put("name","sim返现(77元)");
        seventySeven.put("id","seventySeven");
        seventySeven.put("flowFee",bizMerchant.getMerchId() == 2L?77:posMachineMapper.getMinEachFlowFee("seventy_seven",snList,bizMerchant.getMerchId()));
        flowFeeList.add(seventySeven);

        JSONObject seventyEight = new JSONObject();
        seventyEight.put("name","sim返现(78元)");
        seventyEight.put("id","seventyEight");
        seventyEight.put("flowFee",bizMerchant.getMerchId() == 2L?78:posMachineMapper.getMinEachFlowFee("seventy_eight",snList,bizMerchant.getMerchId()));
        flowFeeList.add(seventyEight);

        JSONObject eightyEight = new JSONObject();
        eightyEight.put("name","sim返现(88元)");
        eightyEight.put("id","eightyEight");
        eightyEight.put("flowFee",bizMerchant.getMerchId() == 2L?88:posMachineMapper.getMinEachFlowFee("eighty_eight",snList,bizMerchant.getMerchId()));
        flowFeeList.add(eightyEight);

        JSONObject ninetyEight = new JSONObject();
        ninetyEight.put("name","sim返现(98元)");
        ninetyEight.put("id","ninetyEight");
        ninetyEight.put("flowFee",bizMerchant.getMerchId() == 2L?98:posMachineMapper.getMinEachFlowFee("ninety_eight",snList,bizMerchant.getMerchId()));
        flowFeeList.add(ninetyEight);

        JSONObject ninetyNine = new JSONObject();
        ninetyNine.put("name","sim返现(99元)");
        ninetyNine.put("id","ninetyNine");
        ninetyNine.put("flowFee",bizMerchant.getMerchId() == 2L?99:posMachineMapper.getMinEachFlowFee("ninety_nine",snList,bizMerchant.getMerchId()));
        flowFeeList.add(ninetyNine);

        jsonObject.put("flowFeeList",flowFeeList);
        return AjaxResult.success("划拨范围值",jsonObject);
    }

    @Override
    public AjaxResult posMachineTransferRecords(BizTransferRecords bizTransferRecords) {
        List<BizTransferRecords> bizTransferRecords1 = posMachineMapper.posMachineTransferRecords(bizTransferRecords);
        for(BizTransferRecords sd : bizTransferRecords1){
            int detailCount = posMachineMapper.getDetailCount(sd.getDetailId());
            sd.setCount(detailCount);
        }
        return AjaxResult.success("划拨记录", bizTransferRecords1);
    }

    @Override
    public AjaxResult posMachineUnActiveList(BizPosMachine bizPosMachine) {
        Long userId = bizPosMachine.getUserId();
        BizMerchant bizMerchant = iBizMerchantService.getMerchantByUserId(userId);
        List<BizPosMachine> bizPosMachines = posMachineMapper.posMachineUnActiveList(bizMerchant.getMerchId(),bizPosMachine.getChannel(),bizPosMachine.getPosCode());
        return AjaxResult.success(String.valueOf(bizPosMachines.size()),bizPosMachines);
    }


    @Override
    public AjaxResult channelList(){
        List<BizChannel> bizChannelList = posMachineMapper.getChannelList();
        return AjaxResult.success("渠道列表",bizChannelList);
    }

    @Override
    public AjaxResult posMachineTransferDetail(BizTransferRecords bizTransferRecords) {
        AjaxResult ajaxResult = AjaxResult.success("划拨明细");
        List<BizTransferRecordsDetail> detailList = posMachineMapper.getPosMachineTransferDetail(bizTransferRecords);
        bizTransferRecords = posMachineMapper.getTransferRecords(bizTransferRecords);
        ajaxResult.put("type",bizTransferRecords.getType());
        ajaxResult.put("receiver",bizTransferRecords.getReceiver());
        ajaxResult.put("transfer_time",bizTransferRecords.getTransferTimeStr());
        ajaxResult.put("count",detailList.size());
        ajaxResult.put("detailList",detailList);
        return ajaxResult;
    }

    @Override
    public AjaxResult pictureStore(BizPictureStore bizPictureStore) {
        List<BizPictureStore> imgList = posMachineMapper.getPictureList(bizPictureStore);
        return AjaxResult.success("素材库",imgList);
    }

    @Override
    public AjaxResult pictureBackChannels() {
        List<BizPictureStore> channelList = posMachineMapper.pictureBackChannels();
        return AjaxResult.success("素材库类型",channelList);
    }

    @Override
    public CustomerCashBackTemp getCCBTPolicy(Long customerCashBackId) {
        return posMachineMapper.getCCBTPolicy(customerCashBackId);
    }

    @Override
    public TeamOverviewDTO selectPosNumAndActiveNum(Long merchId, String channel, String format) {
        return posMachineMapper.selectPosNumAndActiveNum( merchId,  channel,  format);
    }

    @Override
    public AjaxResult backPosCodeList(PosTerminalDTO posTerminalDTO) {
        AjaxResult ajaxResult = new AjaxResult();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Long userId = sysUser.getUserId();
        BizMerchant bizMerchant = bizMerchantMapper.selectInfoByUserId(userId);
        posTerminalDTO.setMerchId(bizMerchant.getMerchId());
        posTerminalDTO.setPageNo((posTerminalDTO.getPageNo() - 1) * posTerminalDTO.getPageSize());
        List<BizPosMachine> posList = posMachineMapper.getBackPosCodeList(posTerminalDTO);
        int count = posMachineMapper.getBackPosCodeSize(posTerminalDTO);
        ajaxResult.put("code",200);
        ajaxResult.put("msg","回调列表");
        ajaxResult.put("count",count);
        ajaxResult.put("data",posList);
        ajaxResult.put("name",sysUser.getNickName());
        return ajaxResult;
    }

    @Override
    public AjaxResult backPosCode(AllocationRelation allocationRelation) {
        List<Long> posIdsList = allocationRelation.getPosIds();
        if(posIdsList.size() <= 0){
            return AjaxResult.success("未勾选设备");
        }
        List<String> snList = posMachineMapper.getSnListByIds(posIdsList);
        BizPosMachine bizPosMachine = posMachineMapper.selectPosMachineBySn(snList.get(0));
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        BizTransferRecords bizTransferRecords = new BizTransferRecords();
        bizTransferRecords.setType("APP回调");
        bizTransferRecords.setReceiver(sysUser.getNickName()+"-"+sysUser.getPhonenumber());
        String detailId = UUID.randomUUID().toString().replace("-","").toUpperCase();
        bizTransferRecords.setDetailId(detailId);
        bizTransferRecords.setTransferTime(new Date());
        bizTransferRecords.setChannel(bizPosMachine.getChannel());
        BizMerchant bizMerchant = iBizMerchantService.getMerchantByUserId(sysUser.getUserId());
        bizTransferRecords.setUserId(bizMerchant.getUserId());
        posMachineMapper.insertIntoTrscords(bizTransferRecords);
        allocationRelation.setDetailId(detailId);
        for(String sn : snList){
            if(bizMerchant.getMerchId() == 2){//服务中心 全删
                iAllocationRelationService.deleteBySn(sn);
            }else{
                // 查划拨记录, 我的level
                AllocationRelation allocationRelation_mine = iAllocationRelationService.selectInfoBySnAndMerchId(sn,bizMerchant.getMerchId());
                if(allocationRelation_mine != null){
                    Long level = allocationRelation_mine.getLevel();
                    //查询 level大于我的   d0,一次流量费,二次流量费 ,押金,封顶,达标奖励 以及 调价分成  合计
                    AllocationRelation allocationRelation_back = iAllocationRelationService.selectGreaterThanMyLevel(sn,level);
                    // 把d0,一次流量费,二次流量费 ,押金,封顶,达标奖励 以及 调价分成还给我
                    allocationRelation_mine.setD0Fee(allocationRelation_mine.getD0Fee().add(allocationRelation_back.getD0Fee()));
//                    allocationRelation_mine.setSimFee(allocationRelation_mine.getSimFee().add(allocationRelation_back.getSimFee()));
//                    allocationRelation_mine.setSimFeeLast(allocationRelation_mine.getSimFeeLast().add(allocationRelation_back.getSimFeeLast()));
                    allocationRelation_mine.setServiceFee(allocationRelation_mine.getServiceFee().add(allocationRelation_back.getServiceFee()));
                    allocationRelation_mine.setDebitCap(allocationRelation_mine.getDebitCap().add(allocationRelation_back.getDebitCap()));
                    allocationRelation_mine.setCommission(String.valueOf(new BigDecimal(allocationRelation_mine.getCommission()).add(new BigDecimal(allocationRelation_back.getCommission()))));
                    allocationRelation_mine.setStandardCashback(allocationRelation_mine.getStandardCashback().add(allocationRelation_back.getStandardCashback()));
                    allocationRelation_mine.setVip(allocationRelation_mine.getVip().add(allocationRelation_back.getVip()));
                    // 流量费
                    allocationRelation_mine.setFortyEight(allocationRelation_mine.getFortyEight().add(allocationRelation_back.getFortyEight()));
                    allocationRelation_mine.setFiftyEight(allocationRelation_mine.getFiftyEight().add(allocationRelation_back.getFiftyEight()));
                    allocationRelation_mine.setSixty(allocationRelation_mine.getSixty().add(allocationRelation_back.getSixty()));
                    allocationRelation_mine.setSixtyEight(allocationRelation_mine.getSixtyEight().add(allocationRelation_back.getSixtyEight()));
                    allocationRelation_mine.setSeventySeven(allocationRelation_mine.getSeventySeven().add(allocationRelation_back.getSeventySeven()));
                    allocationRelation_mine.setSeventyEight(allocationRelation_mine.getSeventyEight().add(allocationRelation_back.getSeventyEight()));
                    allocationRelation_mine.setEightyEight(allocationRelation_mine.getEightyEight().add(allocationRelation_back.getEightyEight()));
                    allocationRelation_mine.setNinetyEight(allocationRelation_mine.getNinetyEight().add(allocationRelation_back.getNinetyEight()));
                    allocationRelation_mine.setNinetyNine(allocationRelation_mine.getNinetyNine().add(allocationRelation_back.getNinetyNine()));
                    iAllocationRelationService.saveOrUpdate(allocationRelation_mine);
                    //该设备的记录 level大于我的,都删除,
                    iAllocationRelationService.deleteGreaterThanMyLevel(sn,level);
                }
            }
            // 设备merchId改成我
            posMachineMapper.updateMerchIdBySn(sn,bizMerchant.getMerchId());
            //存 回调明细
            BizTransferRecordsDetail btrd = new BizTransferRecordsDetail();
            btrd.setTransferId(allocationRelation.getDetailId());
            btrd.setSn(sn);
            bizPosMachineMapper.insertIntoTrscordsDetails(btrd);
        }
        return AjaxResult.success("回调结束");
    }


    @Override
    public List<BizMercahntFeeNameDTO> echoFeeId5563() {
        return posMachineMapper.selectEchoFeeId5563();
    }


    @Override
    public AjaxResult backPosCodeIntervalList(PosTerminalDTO posTerminalDTO) {
        AjaxResult ajaxResult = new AjaxResult();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Long userId = sysUser.getUserId();
        BizMerchant bizMerchant = bizMerchantMapper.selectInfoByUserId(userId);
        posTerminalDTO.setMerchId(bizMerchant.getMerchId());
        List<BizPosMachine> posList = posMachineMapper.backPosCodeIntervalList(posTerminalDTO);
        ajaxResult.put("code",200);
        ajaxResult.put("msg","回调列表");
        ajaxResult.put("count",posList.size());
        ajaxResult.put("data",posList);
        ajaxResult.put("name",sysUser.getNickName());
        return ajaxResult;
    }

    @Override
    public void updateFee(String deviceSn, String feeId) {
        posMachineMapper.updateFee(deviceSn,feeId);
    }

    @Override
    public BizPosMachine getPosMachineBySnCodeNot0SimAmt(String sn){
        return posMachineMapper.getPosMachineBySnCodeNot0SimAmt(sn);
    }

    @Override
    public List<String> getPosByMerchIds() {
        return posMachineMapper.getPosByMerchIds();
    }

    @Override
    public AjaxResult querySettlementTemp(BizPosMachine bizPosMachine) {
        List<SettlementRateTemplate> list = posMachineMapper.querySettlementTemp(bizPosMachine);
        return AjaxResult.success(list);
    }



}

